aid-runtime-python 0.1.185__py3-none-any.whl → 0.1.186__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
@@ -35,19 +35,26 @@ from aid_runtime.agents import (
35
35
  HumanApproval,
36
36
  HumanDecision,
37
37
  InProcessMemoryStore,
38
+ InProcessRunStore,
38
39
  MemoryDefinition,
39
40
  MemoryStore,
40
41
  NonceStore,
41
42
  PendingApproval,
43
+ PostgresRunStore,
42
44
  Principal,
43
45
  RunResult,
44
46
  RunStatus,
47
+ RunStore,
45
48
  RuntimeSpec,
49
+ SqliteRunStore,
46
50
  StepKind,
47
51
  StepRecord,
48
52
  ThreadMemory,
49
53
  ToolSpec,
54
+ new_run_id,
50
55
  nonce_store_from_env,
56
+ run_store_for,
57
+ run_store_from_env,
51
58
  signer_from_env,
52
59
  )
53
60
  from aid_runtime.cache import CompletionCache, cache_key_for
@@ -357,7 +364,7 @@ from aid_runtime.types import (
357
364
  )
358
365
 
359
366
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
360
- __version__ = "0.1.185"
367
+ __version__ = "0.1.186"
361
368
 
362
369
  __all__ = [
363
370
  "AGENT_LABEL",
@@ -475,6 +482,7 @@ __all__ = [
475
482
  "HumanDecision",
476
483
  "InMemoryVectorStore",
477
484
  "InProcessMemoryStore",
485
+ "InProcessRunStore",
478
486
  "IndexSpec",
479
487
  "IngestReport",
480
488
  "JsonSchemaValid",
@@ -515,6 +523,7 @@ __all__ = [
515
523
  "PipelineContext",
516
524
  "PipelineError",
517
525
  "PolicyEvaluationError",
526
+ "PostgresRunStore",
518
527
  "Principal",
519
528
  "PromptNotFoundError",
520
529
  "PromptRegistry",
@@ -550,6 +559,7 @@ __all__ = [
550
559
  "RunOutput",
551
560
  "RunResult",
552
561
  "RunStatus",
562
+ "RunStore",
553
563
  "Runner",
554
564
  "RuntimeSpec",
555
565
  "ScoredChunk",
@@ -560,6 +570,7 @@ __all__ = [
560
570
  "SourceKind",
561
571
  "SourceSpec",
562
572
  "SpendSummary",
573
+ "SqliteRunStore",
563
574
  "Step",
564
575
  "StepCount",
565
576
  "StepKind",
@@ -638,6 +649,7 @@ __all__ = [
638
649
  "local_trace_enabled",
639
650
  "map_step",
640
651
  "metric_names",
652
+ "new_run_id",
641
653
  "nonce_store_from_env",
642
654
  "normalize",
643
655
  "open_connector",
@@ -663,6 +675,8 @@ __all__ = [
663
675
  "route",
664
676
  "rrf_score",
665
677
  "run_evaluation",
678
+ "run_store_for",
679
+ "run_store_from_env",
666
680
  "run_structured",
667
681
  "signer_from_env",
668
682
  "similarity",
@@ -74,6 +74,15 @@ from aid_runtime.agents.resume import (
74
74
  nonce_store_from_env,
75
75
  signer_from_env,
76
76
  )
77
+ from aid_runtime.agents.runs import (
78
+ InProcessRunStore,
79
+ PostgresRunStore,
80
+ RunStore,
81
+ SqliteRunStore,
82
+ new_run_id,
83
+ run_store_for,
84
+ run_store_from_env,
85
+ )
77
86
  from aid_runtime.agents.state import (
78
87
  AgentCheckpoint,
79
88
  CheckpointIntegrity,
@@ -118,6 +127,7 @@ __all__ = [
118
127
  "HumanDecision",
119
128
  "InProcessMemoryStore",
120
129
  "InProcessNonceStore",
130
+ "InProcessRunStore",
121
131
  "ManagedGuardrailSettings",
122
132
  "MemoryDefinition",
123
133
  "MemoryStore",
@@ -126,11 +136,14 @@ __all__ = [
126
136
  "NonceStore",
127
137
  "PendingApproval",
128
138
  "PostgresNonceStore",
139
+ "PostgresRunStore",
129
140
  "Principal",
130
141
  "RunResult",
131
142
  "RunStatus",
143
+ "RunStore",
132
144
  "RuntimeSpec",
133
145
  "SqliteNonceStore",
146
+ "SqliteRunStore",
134
147
  "StepKind",
135
148
  "StepRecord",
136
149
  "ThreadMemory",
@@ -140,9 +153,12 @@ __all__ = [
140
153
  "evaluate_policy",
141
154
  "managed_guardrail_settings",
142
155
  "model_armor_settings",
156
+ "new_run_id",
143
157
  "nonce_store_for",
144
158
  "nonce_store_from_env",
145
159
  "policy_source",
146
160
  "render_context",
161
+ "run_store_for",
162
+ "run_store_from_env",
147
163
  "signer_from_env",
148
164
  ]
@@ -33,6 +33,7 @@ alias. It is never a retry loop: a degraded frame that still does not fit fails.
33
33
 
34
34
  from __future__ import annotations
35
35
 
36
+ import time
36
37
  from collections.abc import Iterable, Mapping, Sequence
37
38
  from dataclasses import dataclass, field
38
39
  from typing import Any
@@ -73,6 +74,7 @@ from aid_runtime.agents.resume import (
73
74
  InProcessNonceStore,
74
75
  NonceStore,
75
76
  )
77
+ from aid_runtime.agents.runs import RunStore, new_run_id
76
78
  from aid_runtime.agents.state import (
77
79
  AgentCheckpoint,
78
80
  HumanDecision,
@@ -207,6 +209,7 @@ class AgentRuntime:
207
209
  limiter: ConcurrencyLimiter | None = None,
208
210
  signer: CheckpointSigner | None = None,
209
211
  nonces: NonceStore | None = None,
212
+ runs: RunStore | None = None,
210
213
  ) -> None:
211
214
  self._spec = spec
212
215
  self._gateway = gateway
@@ -221,6 +224,11 @@ class AgentRuntime:
221
224
  # before: a library embedding it directly is not silently given a key.
222
225
  self._signer = signer
223
226
  self._nonces: NonceStore = nonces if nonces is not None else InProcessNonceStore()
227
+ # Where a paused run is written so a *later process* can continue it. `None` keeps
228
+ # the pre-store behaviour exactly: the checkpoint returns to the caller and the run
229
+ # outlives the request only, so a library embedder is not silently handed a
230
+ # database, and no `run_id` is reported for a run nothing stored.
231
+ self._runs = runs
224
232
  self._guardrails = GuardrailEngine(spec.guardrails, decisions=spec.decisions)
225
233
  self._tools_by_name: dict[str, ToolSpec] = {
226
234
  definition.name: definition for definition in spec.tools.values()
@@ -241,6 +249,7 @@ class AgentRuntime:
241
249
  tracer: Tracer | None = None,
242
250
  signer: CheckpointSigner | None = None,
243
251
  nonces: NonceStore | None = None,
252
+ runs: RunStore | None = None,
244
253
  ) -> AgentRuntime:
245
254
  """Build a runtime from an emitted IR document.
246
255
 
@@ -263,6 +272,7 @@ class AgentRuntime:
263
272
  limiter=limiter,
264
273
  signer=signer,
265
274
  nonces=nonces,
275
+ runs=runs,
266
276
  )
267
277
 
268
278
  @property
@@ -319,7 +329,7 @@ class AgentRuntime:
319
329
  # The refusal is re-raised unchanged: publishing the spend is not a recovery.
320
330
  self._publish_spend(agent.id, start_cost, start_tokens)
321
331
  raise
322
- return self._wrap(outcome, start_cost, start_tokens)
332
+ return await self._store(self._wrap(outcome, start_cost, start_tokens))
323
333
 
324
334
  async def resume(
325
335
  self,
@@ -343,7 +353,59 @@ class AgentRuntime:
343
353
  # Same rule as `run`: a resumed run that fails has been billed too.
344
354
  self._publish_spend(checkpoint.agent_id, start_cost, start_tokens)
345
355
  raise
346
- return self._wrap(outcome, start_cost, start_tokens)
356
+ return await self._store(self._wrap(outcome, start_cost, start_tokens))
357
+
358
+ async def resume_run(
359
+ self,
360
+ run_id: str,
361
+ decision: HumanDecision | str,
362
+ *,
363
+ principal: Principal | None = None,
364
+ ) -> RunResult:
365
+ """Continue a paused run by id, reading its checkpoint from the store.
366
+
367
+ The distinction from :meth:`resume` is where the authority comes from. A caller
368
+ holding a checkpoint holds a capability; a caller naming a ``run_id`` holds only a
369
+ reference, and the store is what turns it back into a run. That makes the stored
370
+ path safe in two ways the hand-back path is not: the body was authored by the app,
371
+ so nothing the caller sends can be resumed after editing; and the row is claimed in
372
+ the write that reads it, so the id resumes once even across replicas.
373
+
374
+ Everything :meth:`resume` checks still happens -- signature, deadline, owner
375
+ binding, nonce -- because the store returns the *same* signed checkpoint the pause
376
+ produced. A refusal is raised before the decision is read, so an unbound caller
377
+ never learns whether their answer would have been accepted.
378
+ """
379
+ if self._runs is None:
380
+ raise ConfigurationError(
381
+ "this runtime was built without a run store, so there is no paused run "
382
+ "to resume by id; declare `agentState` so the app writes one"
383
+ )
384
+ checkpoint = await self._runs.load(run_id=run_id, now=int(time.time()))
385
+ return await self.resume(checkpoint, decision, principal=principal)
386
+
387
+ async def _store(self, result: RunResult) -> RunResult:
388
+ """Write a paused run and report the id it can be resumed by.
389
+
390
+ Only a pause is stored. A completed run has nothing to continue, and a run that
391
+ hit a ceiling is a failure the caller should see rather than a checkpoint to keep.
392
+ An unsigned checkpoint has no deadline inside it, so ``expires_at`` is ``None``
393
+ rather than a number this method invented: a document that declared no signing key
394
+ declared no window either, and the store records that instead of guessing.
395
+ """
396
+ if self._runs is None or result.status is not RunStatus.PAUSED:
397
+ return result
398
+ if result.checkpoint is None:
399
+ return result
400
+ integrity = result.checkpoint.integrity
401
+ run_id = new_run_id()
402
+ await self._runs.save(
403
+ run_id=run_id,
404
+ checkpoint=result.checkpoint,
405
+ expires_at=None if integrity is None else integrity.expires_at,
406
+ now=int(time.time()),
407
+ )
408
+ return result.model_copy(update={"run_id": run_id})
347
409
 
348
410
  async def _accept(self, checkpoint: AgentCheckpoint, principal: Principal) -> AgentCheckpoint:
349
411
  """Refuse a checkpoint this app did not issue, has expired, or already spent.
@@ -123,9 +123,11 @@ class CheckpointRefusalError(AidRuntimeError):
123
123
  """A resume body this app will not honour, with a stable machine-readable reason.
124
124
 
125
125
  ``reason`` is one of ``tampered``, ``expired``, ``unbound``, ``replayed`` or
126
- ``unsigned``. It is for the log: the generated route answers every one of them with
127
- the same opaque 403, so a caller cannot use the distinction as an oracle. Library
128
- embedders that want the distinction can read it here.
126
+ ``unsigned``. ``unknown-run`` is raised by the run store instead of the signer, when a
127
+ caller names a ``run_id`` nothing is stored under. Every one of them is for the log:
128
+ the generated route answers all of them with the same opaque 403, so a caller cannot
129
+ use the distinction as an oracle. Library embedders that want the distinction can read
130
+ it here.
129
131
  """
130
132
 
131
133
  def __init__(self, reason: str, message: str) -> None:
@@ -0,0 +1,438 @@
1
+ """Where a paused run waits: the store that outlives the process that paused it.
2
+
3
+ Before this module the checkpoint *was* the only record of a paused run, so the run
4
+ outlived the request and not the process. That is a real failure rather than a
5
+ theoretical one: an approval that takes an hour lands on whichever replica is awake, and
6
+ a pod that restarts between the pause and the answer loses the run entirely -- the
7
+ approver answers a question nobody is listening for, and the work is redone from the
8
+ first prompt.
9
+
10
+ :class:`RunStore` closes that gap. On a pause the loop writes the checkpoint and returns a
11
+ ``run_id``; a later request names the id instead of carrying a signed blob. The stored path
12
+ is *strictly stronger* than the hand-back path it sits beside:
13
+
14
+ * The body is authored by the app, never by the caller. A stored checkpoint cannot be
15
+ edited before it is resumed, because the caller never supplies one -- which is why this
16
+ path is safe even for a document that declares no ``signingKeyEnv``.
17
+ * :meth:`RunStore.load` claims the row atomically, so a ``run_id`` resumes once. The row is
18
+ marked spent in the same transaction that reads it, which is a stronger guarantee than
19
+ the nonce claim it repeats: a nonce is remembered per store, and the claim here and the
20
+ checkpoint's own deadline are settled by the same write.
21
+ * The deadline is the checkpoint's own ``expires_at`` for a signed document, so the store
22
+ cannot extend a pause past what the signature allows. An unsigned document has no
23
+ deadline inside its checkpoint, and the store records ``NULL`` rather than inventing
24
+ one -- a run that never expires is a fact about the document, not something to guess.
25
+
26
+ ``retain_seconds`` is the operator's retention, from ``agentState.ttlHours``. It is a
27
+ different number from the resume window on purpose: a run may be *kept* for a week as
28
+ audit material while only being *resumable* for fifteen minutes, and the build refuses the
29
+ one ordering that cannot work -- a retention shorter than the window it has to outlive
30
+ (``ir/state-retention``).
31
+
32
+ Two limits are stated rather than hidden. This module writes no deletion job: expired
33
+ rows are pruned opportunistically on the next save, which is enough to keep a table from
34
+ growing without deciding an operator's retention policy for them. And a store is not a
35
+ queue: it survives a restart and spans replicas, which is what a resumed request needs,
36
+ but nothing here retries a run or advances one on a timer.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import asyncio
42
+ import json
43
+ import os
44
+ import secrets
45
+ import sqlite3
46
+ from pathlib import Path
47
+ from typing import Any, Protocol, runtime_checkable
48
+
49
+ from aid_runtime.agents.resume import CheckpointRefusalError
50
+ from aid_runtime.agents.state import AgentCheckpoint
51
+ from aid_runtime.errors import ConfigurationError
52
+
53
+ __all__ = [
54
+ "InProcessRunStore",
55
+ "PostgresRunStore",
56
+ "RunStore",
57
+ "SqliteRunStore",
58
+ "new_run_id",
59
+ "run_store_for",
60
+ "run_store_from_env",
61
+ ]
62
+
63
+ #: Bytes of entropy behind a run id. 16 bytes is 128 bits: a run id is unguessable even
64
+ #: though it is not the thing that authorizes a resume -- the owner binding and the
65
+ #: single-use claim are -- because an id that could be enumerated would still tell a
66
+ #: caller that a run exists.
67
+ _RUN_ID_BYTES = 16
68
+
69
+
70
+ def new_run_id() -> str:
71
+ """A fresh, unguessable run id. ``run_`` prefix so a log line names what it is."""
72
+ return f"run_{secrets.token_urlsafe(_RUN_ID_BYTES)}"
73
+
74
+
75
+ @runtime_checkable
76
+ class RunStore(Protocol):
77
+ """Where a paused run is written, and how a resuming request finds it again.
78
+
79
+ ``load`` must be atomic in the same sense :meth:`aid_runtime.agents.resume.NonceStore.claim`
80
+ is: two requests naming the same ``run_id`` may arrive together, and exactly one may
81
+ be told the run is theirs. A store that read the row and then updated it would let both
82
+ resume the same pause, which is the precise bug this store exists to prevent.
83
+ """
84
+
85
+ async def save(
86
+ self,
87
+ *,
88
+ run_id: str,
89
+ checkpoint: AgentCheckpoint,
90
+ expires_at: int | None,
91
+ now: int,
92
+ ) -> None:
93
+ """Write a paused run. ``expires_at`` is the pause deadline, or ``None`` for none."""
94
+
95
+ async def load(self, *, run_id: str, now: int) -> AgentCheckpoint:
96
+ """Claim ``run_id`` and return its checkpoint, or raise why it cannot be resumed.
97
+
98
+ Raises :class:`~aid_runtime.errors.CheckpointRefusalError` with ``unknown-run``,
99
+ ``replayed`` or ``expired``. The reason is for the operator log; the generated
100
+ route answers all three with the same opaque 403, so a caller learns only that
101
+ the id did not work.
102
+ """
103
+
104
+
105
+ def _encode(checkpoint: AgentCheckpoint) -> str:
106
+ return json.dumps(checkpoint.model_dump(mode="json"), separators=(",", ":"), ensure_ascii=False)
107
+
108
+
109
+ def _decode(text: str) -> AgentCheckpoint:
110
+ return AgentCheckpoint.model_validate(json.loads(text))
111
+
112
+
113
+ class InProcessRunStore:
114
+ """A dict, and therefore the same limit the in-process nonce store has.
115
+
116
+ It is what a document that declares no ``agentState`` gets, so a paused run survives
117
+ the request and not the process -- the behaviour every document had before this store
118
+ existed. Nothing is worse than before: the checkpoint still returns to the caller.
119
+ """
120
+
121
+ def __init__(self) -> None:
122
+ self._rows: dict[str, tuple[str, int | None, int | None]] = {}
123
+ self._lock = asyncio.Lock()
124
+
125
+ async def save(
126
+ self,
127
+ *,
128
+ run_id: str,
129
+ checkpoint: AgentCheckpoint,
130
+ expires_at: int | None,
131
+ now: int,
132
+ ) -> None:
133
+ async with self._lock:
134
+ self._rows[run_id] = (_encode(checkpoint), expires_at, None)
135
+
136
+ async def load(self, *, run_id: str, now: int) -> AgentCheckpoint:
137
+ async with self._lock:
138
+ row = self._rows.get(run_id)
139
+ if row is None:
140
+ raise CheckpointRefusalError(
141
+ "unknown-run", f"no paused run is stored under {run_id!r}"
142
+ )
143
+ payload, expires_at, resumed_at = row
144
+ if resumed_at is not None:
145
+ raise CheckpointRefusalError(
146
+ "replayed", f"the run stored under {run_id!r} was already resumed"
147
+ )
148
+ if expires_at is not None and expires_at <= now:
149
+ raise CheckpointRefusalError(
150
+ "expired", f"the run stored under {run_id!r} is past its resume window"
151
+ )
152
+ self._rows[run_id] = (payload, expires_at, now)
153
+ return _decode(payload)
154
+
155
+
156
+ class SqliteRunStore:
157
+ """A file, so a paused run survives the process that paused it.
158
+
159
+ ``UPDATE ... WHERE resumed_at IS NULL`` plus ``rowcount`` is the atomic claim: SQLite
160
+ reports whether this writer was the one that cleared the flag, so two workers sharing
161
+ the file cannot both resume the same pause. The row is read first so the refusal can
162
+ say *why* -- an operator reading the log wants to know whether an approval arrived an
163
+ hour late or arrived twice -- and the update that follows is the decision, not the
164
+ read.
165
+ """
166
+
167
+ def __init__(self, path: str | Path, *, retain_seconds: int | None = None) -> None:
168
+ self._path = Path(path)
169
+ self._retain_seconds = retain_seconds
170
+ self._lock = asyncio.Lock()
171
+
172
+ async def save(
173
+ self,
174
+ *,
175
+ run_id: str,
176
+ checkpoint: AgentCheckpoint,
177
+ expires_at: int | None,
178
+ now: int,
179
+ ) -> None:
180
+ async with self._lock:
181
+ await asyncio.to_thread(self._save, run_id, checkpoint, expires_at, now)
182
+
183
+ async def load(self, *, run_id: str, now: int) -> AgentCheckpoint:
184
+ async with self._lock:
185
+ return _decode(await asyncio.to_thread(self._load, run_id, now))
186
+
187
+ def _retain_until(self, now: int) -> int | None:
188
+ if self._retain_seconds is None:
189
+ return None
190
+ return now + self._retain_seconds
191
+
192
+ def _connect(self) -> sqlite3.Connection:
193
+ self._path.parent.mkdir(parents=True, exist_ok=True)
194
+ connection = sqlite3.connect(self._path)
195
+ connection.execute("PRAGMA journal_mode=WAL")
196
+ connection.execute(
197
+ "CREATE TABLE IF NOT EXISTS agent_run ("
198
+ "run_id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, checkpoint TEXT NOT NULL, "
199
+ "expires_at INTEGER, retain_until INTEGER, created_at INTEGER NOT NULL, "
200
+ "resumed_at INTEGER)"
201
+ )
202
+ return connection
203
+
204
+ def _save(
205
+ self,
206
+ run_id: str,
207
+ checkpoint: AgentCheckpoint,
208
+ expires_at: int | None,
209
+ now: int,
210
+ ) -> None:
211
+ with self._connect() as connection:
212
+ if self._retain_seconds is not None:
213
+ connection.execute(
214
+ "DELETE FROM agent_run WHERE retain_until IS NOT NULL AND retain_until <= ?",
215
+ (now,),
216
+ )
217
+ connection.execute(
218
+ "INSERT OR REPLACE INTO agent_run "
219
+ "(run_id, agent_id, checkpoint, expires_at, retain_until, created_at, "
220
+ "resumed_at) VALUES (?, ?, ?, ?, ?, ?, NULL)",
221
+ (
222
+ run_id,
223
+ checkpoint.agent_id,
224
+ _encode(checkpoint),
225
+ expires_at,
226
+ self._retain_until(now),
227
+ now,
228
+ ),
229
+ )
230
+
231
+ def _load(self, run_id: str, now: int) -> str:
232
+ with self._connect() as connection:
233
+ row = connection.execute(
234
+ "SELECT checkpoint, expires_at, resumed_at FROM agent_run WHERE run_id = ?",
235
+ (run_id,),
236
+ ).fetchone()
237
+ if row is None:
238
+ raise CheckpointRefusalError(
239
+ "unknown-run", f"no paused run is stored under {run_id!r}"
240
+ )
241
+ payload, expires_at, resumed_at = row
242
+ if resumed_at is not None:
243
+ raise CheckpointRefusalError(
244
+ "replayed", f"the run stored under {run_id!r} was already resumed"
245
+ )
246
+ if expires_at is not None and expires_at <= now:
247
+ raise CheckpointRefusalError(
248
+ "expired", f"the run stored under {run_id!r} is past its resume window"
249
+ )
250
+ claimed = connection.execute(
251
+ "UPDATE agent_run SET resumed_at = ? WHERE run_id = ? AND resumed_at IS NULL",
252
+ (now, run_id),
253
+ ).rowcount
254
+ if claimed != 1:
255
+ # Another writer claimed the row between the read and this update.
256
+ raise CheckpointRefusalError(
257
+ "replayed", f"the run stored under {run_id!r} was already resumed"
258
+ )
259
+ return str(payload)
260
+
261
+
262
+ class PostgresRunStore:
263
+ """The same claim in the database a ``state.kind: postgres`` document already names.
264
+
265
+ ``ON CONFLICT (run_id) DO UPDATE`` makes a save idempotent, so a retried write cannot
266
+ fail on a duplicate key, and ``UPDATE ... WHERE resumed_at IS NULL RETURNING`` makes
267
+ the claim atomic across replicas -- which is the only place it can be atomic, since the
268
+ next request may land anywhere. The driver is optional, following the nonce store: a
269
+ deployment that never declares ``postgres`` pays nothing for it.
270
+ """
271
+
272
+ def __init__(self, dsn: str, *, retain_seconds: int | None = None) -> None:
273
+ self._dsn = dsn
274
+ self._retain_seconds = retain_seconds
275
+ self._lock = asyncio.Lock()
276
+ self._ready = False
277
+
278
+ async def save(
279
+ self,
280
+ *,
281
+ run_id: str,
282
+ checkpoint: AgentCheckpoint,
283
+ expires_at: int | None,
284
+ now: int,
285
+ ) -> None:
286
+ async with self._lock:
287
+ await asyncio.to_thread(self._save, run_id, checkpoint, expires_at, now)
288
+
289
+ async def load(self, *, run_id: str, now: int) -> AgentCheckpoint:
290
+ async with self._lock:
291
+ return _decode(await asyncio.to_thread(self._load, run_id, now))
292
+
293
+ def _retain_until(self, now: int) -> int | None:
294
+ if self._retain_seconds is None:
295
+ return None
296
+ return now + self._retain_seconds
297
+
298
+ def _connect(self) -> Any:
299
+ psycopg = _load_psycopg()
300
+ connection = psycopg.connect(self._dsn)
301
+ if not self._ready:
302
+ connection.execute(
303
+ "CREATE TABLE IF NOT EXISTS agent_run ("
304
+ "run_id TEXT PRIMARY KEY, agent_id TEXT NOT NULL, checkpoint TEXT NOT NULL, "
305
+ "expires_at BIGINT, retain_until BIGINT, created_at BIGINT NOT NULL, "
306
+ "resumed_at BIGINT)"
307
+ )
308
+ self._ready = True
309
+ return connection
310
+
311
+ def _save(
312
+ self,
313
+ run_id: str,
314
+ checkpoint: AgentCheckpoint,
315
+ expires_at: int | None,
316
+ now: int,
317
+ ) -> None:
318
+ with self._connect() as connection:
319
+ if self._retain_seconds is not None:
320
+ connection.execute(
321
+ "DELETE FROM agent_run WHERE retain_until IS NOT NULL AND retain_until <= %s",
322
+ (now,),
323
+ )
324
+ connection.execute(
325
+ "INSERT INTO agent_run "
326
+ "(run_id, agent_id, checkpoint, expires_at, retain_until, created_at, "
327
+ "resumed_at) VALUES (%s, %s, %s, %s, %s, %s, NULL) "
328
+ "ON CONFLICT (run_id) DO UPDATE SET checkpoint = EXCLUDED.checkpoint, "
329
+ "expires_at = EXCLUDED.expires_at, retain_until = EXCLUDED.retain_until",
330
+ (
331
+ run_id,
332
+ checkpoint.agent_id,
333
+ _encode(checkpoint),
334
+ expires_at,
335
+ self._retain_until(now),
336
+ now,
337
+ ),
338
+ )
339
+
340
+ def _load(self, run_id: str, now: int) -> str:
341
+ with self._connect() as connection:
342
+ row = connection.execute(
343
+ "SELECT checkpoint, expires_at, resumed_at FROM agent_run WHERE run_id = %s",
344
+ (run_id,),
345
+ ).fetchone()
346
+ if row is None:
347
+ raise CheckpointRefusalError(
348
+ "unknown-run", f"no paused run is stored under {run_id!r}"
349
+ )
350
+ _payload, expires_at, resumed_at = row
351
+ if resumed_at is not None:
352
+ raise CheckpointRefusalError(
353
+ "replayed", f"the run stored under {run_id!r} was already resumed"
354
+ )
355
+ if expires_at is not None and expires_at <= now:
356
+ raise CheckpointRefusalError(
357
+ "expired", f"the run stored under {run_id!r} is past its resume window"
358
+ )
359
+ claimed = connection.execute(
360
+ "UPDATE agent_run SET resumed_at = %s WHERE run_id = %s AND resumed_at IS NULL "
361
+ "RETURNING checkpoint",
362
+ (now, run_id),
363
+ ).fetchone()
364
+ if claimed is None:
365
+ raise CheckpointRefusalError(
366
+ "replayed", f"the run stored under {run_id!r} was already resumed"
367
+ )
368
+ return str(claimed[0])
369
+
370
+
371
+ def _load_psycopg() -> Any:
372
+ """Import the optional driver, or explain how to install it."""
373
+ try:
374
+ import psycopg
375
+ except ImportError as error:
376
+ raise ConfigurationError(
377
+ "a `state: postgres` declaration needs its driver to store a paused run; "
378
+ "install it with `pip install aid-runtime-python[pgvector]` (the default "
379
+ "install omits psycopg)"
380
+ ) from error
381
+ return psycopg
382
+
383
+
384
+ def run_store_for(
385
+ kind: str | None,
386
+ location: str | None,
387
+ *,
388
+ retain_seconds: int | None = None,
389
+ ) -> RunStore:
390
+ """The most durable run store this build can offer for a declared ``state``.
391
+
392
+ No declaration -- or a location that was not resolved from the environment -- falls
393
+ back to the in-process store, which is exactly what such a document declared: a run
394
+ that outlives the request and not the process. ``ir/resume-replay-weak`` reports it
395
+ rather than this function raising, because a library embedding the loop must not be
396
+ forced to own a database it never asked for.
397
+ """
398
+ if location:
399
+ if kind == "sqlite":
400
+ return SqliteRunStore(location, retain_seconds=retain_seconds)
401
+ if kind == "postgres":
402
+ return PostgresRunStore(location, retain_seconds=retain_seconds)
403
+ return InProcessRunStore()
404
+
405
+
406
+ def run_store_from_env(
407
+ kind: str | None,
408
+ variable: str | None,
409
+ *,
410
+ retain_seconds: int | None = None,
411
+ ) -> RunStore:
412
+ """The store a generated app builds from the variable its ``agentState`` names.
413
+
414
+ Resolved at request time rather than import, like every other credential this app
415
+ reads: a supervisor that sets the variable before the first request is the normal
416
+ deployment shape, and a module that opened a database at import could not be imported
417
+ by a test that only wants ``DOCUMENT``.
418
+
419
+ An unresolvable variable is refused by name, the same way
420
+ :func:`aid_runtime.agents.resume.signer_from_env` refuses an unset signing key. The
421
+ alternative -- quietly storing the run in one worker's memory -- would withdraw the
422
+ durability the build gate promised while looking like it worked.
423
+ """
424
+ if kind is None:
425
+ return InProcessRunStore()
426
+ if variable is None:
427
+ raise ConfigurationError(
428
+ f"this app's state kind is {kind!r} but no urlEnv names where it lives; "
429
+ "declare agentState.urlEnv so a paused run can be stored durably"
430
+ )
431
+ location = os.environ.get(variable, "")
432
+ if not location:
433
+ raise ConfigurationError(
434
+ f"{variable} is not set, but this app declares a {kind} state store; set it to "
435
+ "the connection string or file path, so a paused run is written where the next "
436
+ "request can read it"
437
+ )
438
+ return run_store_for(kind, location, retain_seconds=retain_seconds)
@@ -192,6 +192,11 @@ class RunResult(BaseModel):
192
192
  cost_usd: float = Field(default=0.0, ge=0.0)
193
193
  total_tokens: int = Field(default=0, ge=0)
194
194
  checkpoint: AgentCheckpoint | None = None
195
+ # The id a paused run was stored under, when the runtime was given a store. Empty
196
+ # otherwise, which is the honest answer for a document that declared no
197
+ # `agentState`: the run outlived the request and nothing more. `checkpoint` stays
198
+ # populated in both cases, so a caller that ignores this field keeps working.
199
+ run_id: str = ""
195
200
  guardrails: tuple[GuardrailRecord, ...] = ()
196
201
 
197
202
  @property
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.185
3
+ Version: 0.1.186
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=OVFgO7Wlbpie7DqzlGb3kbbB-sKQ-gpg_kErON-UeGQ,15277
1
+ aid_runtime/__init__.py,sha256=fIEoST13MhLL6uJXv8rbiKRRocvcSpAYAV5wNJ92etk,15567
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,18 +18,19 @@ 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=ErdKuLaHi0rfN4Z3IE0akevF7W6-RH4F-i7LxCqziDE,3825
21
+ aid_runtime/agents/__init__.py,sha256=iSDBuG0oFJmvhayWuwOdHwJEPiofJkrgPd2Hu3rJyLE,4155
22
22
  aid_runtime/agents/chat_model.py,sha256=RHMA3_Yb8UE14YQo8k-ylUZiQnOvUKDnl1AEKBG_rgU,16526
23
23
  aid_runtime/agents/deep_agents.py,sha256=MNx75AWoT5qfLOzhsa6iggu455VUJaS8tYdeFayTHLc,27648
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=kBCvMYrLAS6umkl_JK-JwJhOxvDRXLV0wiZ_r6CgvII,34088
27
- aid_runtime/agents/loop.py,sha256=WVQZd7XWmjGC1c5DE9M-OQd90REKvuYlyiqsRYtT_YY,60809
27
+ aid_runtime/agents/loop.py,sha256=OyWyotVd4sDRSFQMVXlTmx2rBZR7Yo-A3W4addQnr7A,64023
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=NRdIhGK-DkYra71l__dRyGgDaRWyPn0dCpwoY2WN1C4,7054
31
- aid_runtime/agents/resume.py,sha256=Y84E4D5tAsurUqQtzbba-4QipkWXxSYRZ9PxE2zM-Vk,26713
32
- aid_runtime/agents/state.py,sha256=_31WuSYVlZRS3MvFN_ZZA5SozpO9B1-aujecu1ARisY,7629
31
+ aid_runtime/agents/resume.py,sha256=4unbYRL4Hg0hawE84YLgGvd-in7DfP9gH5cPmRLr8Uc,26854
32
+ aid_runtime/agents/runs.py,sha256=P_3AStEPUtzOM_NvOKFuvo8JZymr8JLrViMNgQSrUW8,18090
33
+ aid_runtime/agents/state.py,sha256=3ZMf-z17vuWJ0Svh-koR213Y4T2OCFpvrTaKSgzn0iQ,7980
33
34
  aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
34
35
  aid_runtime/evals/agent_runner.py,sha256=sffFGqZDBLmKkce6t82IaWJLHNq-q7HuSmIM61uEkoU,13513
35
36
  aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
@@ -63,7 +64,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
63
64
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
64
65
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
65
66
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
66
- aid_runtime_python-0.1.185.dist-info/METADATA,sha256=irtgIMRBsrVYBvfI4heacSJY8scwFvFb07jrwNBq29U,17163
67
- aid_runtime_python-0.1.185.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
- aid_runtime_python-0.1.185.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
- aid_runtime_python-0.1.185.dist-info/RECORD,,
67
+ aid_runtime_python-0.1.186.dist-info/METADATA,sha256=2XmpEuiu7ENP456s4bYbk7MyYUiw48GbqI8clSdvFZY,17163
68
+ aid_runtime_python-0.1.186.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
69
+ aid_runtime_python-0.1.186.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
70
+ aid_runtime_python-0.1.186.dist-info/RECORD,,