aid-runtime-python 0.1.162__py3-none-any.whl → 0.1.163__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.163"
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
@@ -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
@@ -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.
@@ -0,0 +1,398 @@
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` is durable and is what a ``state.kind: sqlite`` declaration
28
+ gets. A ``state.kind: postgres`` declaration is served in-process for now, which the
29
+ ``ir/resume-replay-weak`` gate states on the document rather than leaving to be
30
+ discovered.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ import hashlib
37
+ import hmac
38
+ import json
39
+ import os
40
+ import secrets
41
+ import sqlite3
42
+ import time
43
+ from dataclasses import dataclass, field
44
+ from pathlib import Path
45
+ from typing import Any, Protocol, runtime_checkable
46
+
47
+ from aid_runtime.agents.state import AgentCheckpoint, CheckpointIntegrity
48
+ from aid_runtime.errors import AidRuntimeError, ConfigurationError
49
+
50
+ __all__ = [
51
+ "DEFAULT_CHECKPOINT_TTL_MINUTES",
52
+ "CheckpointRefusalError",
53
+ "CheckpointSigner",
54
+ "InProcessNonceStore",
55
+ "NonceStore",
56
+ "PostgresNonceStore",
57
+ "SqliteNonceStore",
58
+ "checkpoint_payload",
59
+ "nonce_store_for",
60
+ "signer_from_env",
61
+ ]
62
+
63
+ #: How long a checkpoint stays usable. Short on purpose: a pause is a question asked of
64
+ #: a person in the same change window, not a durable queue.
65
+ DEFAULT_CHECKPOINT_TTL_MINUTES = 15
66
+
67
+
68
+ class CheckpointRefusalError(AidRuntimeError):
69
+ """A resume body this app will not honour, with a stable machine-readable reason.
70
+
71
+ ``reason`` is one of ``tampered``, ``expired``, ``replayed``, ``unsigned``. The
72
+ generated route maps it to a 403 and returns it as ``detail.reason``, so a caller can
73
+ tell "your checkpoint expired" from "your checkpoint was edited" without parsing
74
+ prose.
75
+ """
76
+
77
+ def __init__(self, reason: str, message: str) -> None:
78
+ super().__init__(message)
79
+ self.reason = reason
80
+
81
+
82
+ @runtime_checkable
83
+ class NonceStore(Protocol):
84
+ """Remembers which checkpoints have been spent.
85
+
86
+ ``claim`` must be atomic: two concurrent requests presenting the same checkpoint may
87
+ both reach it, and exactly one must be told ``True``. A store that reads then writes
88
+ would let both through.
89
+ """
90
+
91
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
92
+ """``True`` the first time ``nonce`` is seen, ``False`` every time after.
93
+
94
+ ``now`` is the caller's clock, not this store's, so the pruning horizon and the
95
+ expiry the signer checked cannot disagree. A store that read the wall clock while
96
+ the signer took an injected one would prune a row before the replay check and
97
+ accept the replay.
98
+ """
99
+ ...
100
+
101
+
102
+ class InProcessNonceStore:
103
+ """A dict, and therefore a limit worth stating.
104
+
105
+ It is the honest default: a library must not decide where a host keeps its data. It
106
+ survives neither a restart nor a second replica, so a checkpoint replayed against
107
+ another worker is accepted there. ``profile: enterprise`` with no declared ``state``
108
+ is refused by ``ir/resume-replay-weak`` for exactly this reason.
109
+ """
110
+
111
+ def __init__(self) -> None:
112
+ self._seen: dict[str, int] = {}
113
+ self._lock = asyncio.Lock()
114
+
115
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
116
+ async with self._lock:
117
+ self._seen = {seen: expiry for seen, expiry in self._seen.items() if expiry > now}
118
+ if nonce in self._seen:
119
+ return False
120
+ self._seen[nonce] = expires_at
121
+ return True
122
+
123
+
124
+ class SqliteNonceStore:
125
+ """A file, and therefore durable across a restart.
126
+
127
+ ``INSERT OR IGNORE`` is the atomic claim: SQLite reports whether it inserted, so two
128
+ workers sharing the file cannot both see ``True``. This is what a ``state.kind:
129
+ sqlite`` declaration is served by, because that declaration already means "a file on
130
+ a volume this process can reach".
131
+ """
132
+
133
+ def __init__(self, path: str | Path) -> None:
134
+ self._path = Path(path)
135
+ self._lock = asyncio.Lock()
136
+
137
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
138
+ async with self._lock:
139
+ return await asyncio.to_thread(self._claim, nonce, expires_at, now)
140
+
141
+ def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
142
+ self._path.parent.mkdir(parents=True, exist_ok=True)
143
+ with sqlite3.connect(self._path) as connection:
144
+ connection.execute("PRAGMA journal_mode=WAL")
145
+ connection.execute(
146
+ "CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
147
+ "nonce TEXT PRIMARY KEY, expires_at INTEGER NOT NULL)"
148
+ )
149
+ connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= ?", (now,))
150
+ cursor = connection.execute(
151
+ "INSERT OR IGNORE INTO checkpoint_nonce (nonce, expires_at) VALUES (?, ?)",
152
+ (nonce, expires_at),
153
+ )
154
+ return cursor.rowcount == 1
155
+
156
+
157
+ class PostgresNonceStore:
158
+ """The same claim in the database the document already names.
159
+
160
+ ``state.kind: postgres`` is the enterprise answer, so replay protection has to live
161
+ there rather than in a process: the whole point of a shared store is that the next
162
+ request may land anywhere. ``ON CONFLICT DO NOTHING`` plus ``RETURNING`` makes the
163
+ claim atomic in the database, which is the only place a claim can be atomic across
164
+ replicas.
165
+
166
+ The driver is optional, following the pgvector store: a deployment that never
167
+ declares `postgres` pays nothing for it, and one that does is told which extra to
168
+ install rather than discovering it at the first paused run.
169
+ """
170
+
171
+ def __init__(self, dsn: str) -> None:
172
+ self._dsn = dsn
173
+ self._lock = asyncio.Lock()
174
+ self._ready = False
175
+
176
+ async def claim(self, *, nonce: str, expires_at: int, now: int) -> bool:
177
+ async with self._lock:
178
+ return await asyncio.to_thread(self._claim, nonce, expires_at, now)
179
+
180
+ def _claim(self, nonce: str, expires_at: int, now: int) -> bool:
181
+ psycopg = _load_psycopg()
182
+ with psycopg.connect(self._dsn) as connection:
183
+ if not self._ready:
184
+ connection.execute(
185
+ "CREATE TABLE IF NOT EXISTS checkpoint_nonce ("
186
+ "nonce TEXT PRIMARY KEY, expires_at BIGINT NOT NULL)"
187
+ )
188
+ self._ready = True
189
+ connection.execute("DELETE FROM checkpoint_nonce WHERE expires_at <= %s", (now,))
190
+ row = connection.execute(
191
+ "INSERT INTO checkpoint_nonce (nonce, expires_at) VALUES (%s, %s) "
192
+ "ON CONFLICT (nonce) DO NOTHING RETURNING nonce",
193
+ (nonce, expires_at),
194
+ ).fetchone()
195
+ return row is not None
196
+
197
+
198
+ def _load_psycopg() -> Any:
199
+ """Import the optional driver, or explain how to install it."""
200
+ try:
201
+ import psycopg
202
+ except ImportError as error:
203
+ raise ConfigurationError(
204
+ "a `state: postgres` declaration needs its driver for replay protection; "
205
+ "install it with `pip install aid-runtime-python[pgvector]` (the default "
206
+ "install omits psycopg)"
207
+ ) from error
208
+ return psycopg
209
+
210
+
211
+ def checkpoint_payload(checkpoint: AgentCheckpoint) -> bytes:
212
+ """The canonical bytes a signature covers.
213
+
214
+ Everything except the signature itself. That includes the integrity block's own
215
+ ``issued_at``, ``expires_at`` and ``nonce``: leaving those out would let a holder
216
+ move their deadline forward, and would let them swap the nonce of an already-spent
217
+ checkpoint to walk past replay protection. The pending calls, the approval channel
218
+ and the nested ``caller`` frames are inside too, so one signature binds all of them.
219
+ Sorted keys and no separator padding make the encoding reproducible in a second
220
+ process, which a signature requires.
221
+ """
222
+ document = checkpoint.model_dump(mode="json", exclude={"integrity": {"signature"}})
223
+ return json.dumps(
224
+ document,
225
+ sort_keys=True,
226
+ separators=(",", ":"),
227
+ ensure_ascii=False,
228
+ default=str,
229
+ ).encode("utf-8")
230
+
231
+
232
+ @dataclass(frozen=True, slots=True)
233
+ class CheckpointSigner:
234
+ """HMAC-SHA256 over :func:`checkpoint_payload`, plus the expiry it records.
235
+
236
+ ``secret`` is read from the environment by the caller; it is never a spec value. The
237
+ dataclass is frozen and holds no mutable state, so one instance can be shared across
238
+ requests and a test can construct its own without touching the process environment.
239
+ """
240
+
241
+ secret: str = field(repr=False)
242
+ ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
243
+
244
+ def __post_init__(self) -> None:
245
+ if not self.secret:
246
+ raise ValueError(
247
+ "CheckpointSigner needs a non-empty secret; an empty key would sign "
248
+ "every checkpoint identically"
249
+ )
250
+ if self.ttl_seconds <= 0:
251
+ raise ValueError("CheckpointSigner needs a positive ttl_seconds")
252
+
253
+ def _mac(self, payload: bytes) -> str:
254
+ return hmac.new(self.secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
255
+
256
+ def _digest(self, checkpoint: AgentCheckpoint) -> str:
257
+ """The MAC of ``checkpoint`` excluding only the signature field.
258
+
259
+ Signing and verifying both go through here, so the two sides cannot drift into
260
+ covering different bytes: a signature that verifies against a payload it was not
261
+ computed over would accept an edited checkpoint.
262
+ """
263
+ return self._mac(checkpoint_payload(checkpoint))
264
+
265
+ def sign(
266
+ self,
267
+ checkpoint: AgentCheckpoint,
268
+ *,
269
+ now: int | None = None,
270
+ nonce: str | None = None,
271
+ ) -> AgentCheckpoint:
272
+ """Return a copy of ``checkpoint`` carrying a fresh integrity block.
273
+
274
+ ``now`` and ``nonce`` exist for tests; production passes neither. The return is a
275
+ new frozen model, so a caller that kept the unsigned value still has it.
276
+ """
277
+ issued_at = int(time.time()) if now is None else int(now)
278
+ integrity = CheckpointIntegrity(
279
+ issued_at=issued_at,
280
+ expires_at=issued_at + self.ttl_seconds,
281
+ nonce=secrets.token_urlsafe(24) if nonce is None else nonce,
282
+ signature="",
283
+ )
284
+ unsigned = checkpoint.model_copy(update={"integrity": integrity})
285
+ signature = self._digest(unsigned)
286
+ return checkpoint.model_copy(
287
+ update={"integrity": integrity.model_copy(update={"signature": signature})}
288
+ )
289
+
290
+ def verify(self, checkpoint: AgentCheckpoint, *, now: int | None = None) -> CheckpointIntegrity:
291
+ """Check signature and expiry. Returns the integrity block, or raises.
292
+
293
+ Replay is *not* checked here: it needs the store, and therefore an ``await``.
294
+ :meth:`accept` is the full check a request handler wants.
295
+ """
296
+ integrity = checkpoint.integrity
297
+ if integrity is None:
298
+ raise CheckpointRefusalError(
299
+ "unsigned",
300
+ "this checkpoint carries no signature, so it was not issued by an app "
301
+ "built with checkpoint signing",
302
+ )
303
+ expected = self._digest(checkpoint)
304
+ if not hmac.compare_digest(expected, integrity.signature):
305
+ raise CheckpointRefusalError(
306
+ "tampered",
307
+ "this checkpoint's signature does not match its contents; it was edited "
308
+ "after it was issued",
309
+ )
310
+ moment = int(time.time()) if now is None else int(now)
311
+ if integrity.expires_at <= moment:
312
+ raise CheckpointRefusalError(
313
+ "expired",
314
+ f"this checkpoint expired at {integrity.expires_at}; a pause is valid for "
315
+ f"{self.ttl_seconds} seconds, so resume it sooner or start the run again",
316
+ )
317
+ return integrity
318
+
319
+ async def accept(
320
+ self,
321
+ checkpoint: AgentCheckpoint,
322
+ nonces: NonceStore,
323
+ *,
324
+ now: int | None = None,
325
+ ) -> CheckpointIntegrity:
326
+ """Signature, then expiry, then a one-time claim. Raises on any failure."""
327
+ moment = int(time.time()) if now is None else int(now)
328
+ integrity = self.verify(checkpoint, now=moment)
329
+ claimed = await nonces.claim(
330
+ nonce=integrity.nonce, expires_at=integrity.expires_at, now=moment
331
+ )
332
+ if not claimed:
333
+ raise CheckpointRefusalError(
334
+ "replayed",
335
+ "this checkpoint has already been spent; a resume is accepted once, so a "
336
+ "second presentation of the same checkpoint is refused",
337
+ )
338
+ return integrity
339
+
340
+
341
+ def signer_from_env(
342
+ variable: str, *, ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
343
+ ) -> CheckpointSigner:
344
+ """Build a signer from ``os.environ[variable]``, naming the variable when it is unset."""
345
+ secret = os.environ.get(variable, "")
346
+ if not secret:
347
+ raise ConfigurationError(
348
+ f"{variable} is not set, but this app signs its checkpoints; set it to a "
349
+ "high-entropy secret before serving the resume route"
350
+ )
351
+ return CheckpointSigner(secret=secret, ttl_seconds=ttl_seconds)
352
+
353
+
354
+ def nonce_store_for(kind: str | None, location: str | None) -> NonceStore:
355
+ """The most durable nonce store this build can offer for a declared ``state``.
356
+
357
+ Each declared kind claims the nonce where that declaration already points: ``sqlite``
358
+ names a file, ``postgres`` names a database. Both are durable across a restart and
359
+ across replicas. No declaration -- or a location that was not resolved from the
360
+ environment -- falls back to the in-process store, which ``ir/resume-replay-weak``
361
+ reports rather than this function hiding.
362
+ """
363
+ if location:
364
+ if kind == "sqlite":
365
+ return SqliteNonceStore(location)
366
+ if kind == "postgres":
367
+ return PostgresNonceStore(location)
368
+ return InProcessNonceStore()
369
+
370
+
371
+ def nonce_store_from_env(kind: str | None, variable: str | None) -> NonceStore:
372
+ """The store a generated app builds from the variable its ``state`` declaration names.
373
+
374
+ ``nonce_store_for`` falls back to the in-process store when it is handed no location,
375
+ which is right for a library and wrong here: the document declared a durable store, and
376
+ silently claiming the nonce in one worker would withdraw the replay protection the
377
+ build gate promised. So an unresolvable variable is refused by name, the same way
378
+ :func:`signer_from_env` refuses an unset signing key.
379
+
380
+ ``kind`` of ``None`` means the document declared no store at all -- ``standard`` with a
381
+ warning from ``ir/resume-replay-weak`` -- and then the in-process store is exactly what
382
+ was declared, so it is returned rather than refused.
383
+ """
384
+ if kind is None:
385
+ return InProcessNonceStore()
386
+ if variable is None:
387
+ raise ConfigurationError(
388
+ f"this app's state kind is {kind!r} but no urlEnv names where it lives; "
389
+ "declare state.urlEnv so a spent checkpoint can be claimed durably"
390
+ )
391
+ location = os.environ.get(variable, "")
392
+ if not location:
393
+ raise ConfigurationError(
394
+ f"{variable} is not set, but this app declares a {kind} state store; set it to "
395
+ "the connection string or file path, so a spent checkpoint is refused there "
396
+ "rather than only in the process that issued it"
397
+ )
398
+ 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):
@@ -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.163
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=aq8poIy2LFueKsPEbAN84Bi3Z2oETd3b_kvauiwj_Jo,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,17 +18,18 @@ 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=gTfFRcRuGuyZpNdw2PK168A9Cp6LHBLJMUpHUxXPTnE,55952
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
30
  aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
31
- aid_runtime/agents/state.py,sha256=4itT7BWv2JKSeWpRrDyxLguOOVnz9gGH_qgRdCbWCaw,6086
31
+ aid_runtime/agents/resume.py,sha256=VAjJja2ZvXLLSRgz9Z_2b5Cs9Af5Kevr5qjuDpslpuw,17035
32
+ aid_runtime/agents/state.py,sha256=feXZtQeD3vcKpNUPsCXby0J15UqkoD4_Gi-aT3Up8RI,7174
32
33
  aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
33
34
  aid_runtime/evals/agent_runner.py,sha256=E1Vg48gNAeQzGGSyp0cK8H5mxGlVEPBq-FTaaTQ-CLE,12594
34
35
  aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
@@ -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.163.dist-info/METADATA,sha256=XBOwwaxOR6fnCKOlGWFeUYukKzWGBsttWdLvtLCG9Vw,17163
67
+ aid_runtime_python-0.1.163.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
+ aid_runtime_python-0.1.163.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
+ aid_runtime_python-0.1.163.dist-info/RECORD,,