aid-runtime-python 0.1.176__py3-none-any.whl → 0.1.177__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
@@ -357,7 +357,7 @@ from aid_runtime.types import (
357
357
  )
358
358
 
359
359
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
360
- __version__ = "0.1.176"
360
+ __version__ = "0.1.177"
361
361
 
362
362
  __all__ = [
363
363
  "AGENT_LABEL",
@@ -62,6 +62,8 @@ from aid_runtime.agents.memory import (
62
62
  from aid_runtime.agents.policy import Principal, evaluate_policy, policy_source
63
63
  from aid_runtime.agents.resume import (
64
64
  DEFAULT_CHECKPOINT_TTL_MINUTES,
65
+ DEFAULT_CLOCK_LEEWAY_SECONDS,
66
+ MIN_SECRET_BYTES,
65
67
  CheckpointRefusalError,
66
68
  CheckpointSigner,
67
69
  InProcessNonceStore,
@@ -85,11 +87,13 @@ from aid_runtime.agents.state import (
85
87
 
86
88
  __all__ = [
87
89
  "DEFAULT_CHECKPOINT_TTL_MINUTES",
90
+ "DEFAULT_CLOCK_LEEWAY_SECONDS",
88
91
  "DETECTORS",
89
92
  "GUARDRAIL_ACTIONS",
90
93
  "GUARDRAIL_STAGES",
91
94
  "IMPLEMENTED_MEMORY_KINDS",
92
95
  "MEMORY_SCOPES",
96
+ "MIN_SECRET_BYTES",
93
97
  "MODEL_ARMOR_TEMPLATE_ENV",
94
98
  "AgentCheckpoint",
95
99
  "AgentDefinition",
@@ -115,7 +115,7 @@ class DeepAgentsEngine:
115
115
  if not frame.input_checked:
116
116
  frame.input_checked = True
117
117
  paused = await self._runtime._guardrail_text(
118
- _GUARDRAIL_INPUT, frame, memory_key, span=span, rewrite=True
118
+ _GUARDRAIL_INPUT, frame, memory_key, span=span, rewrite=True, principal=principal
119
119
  )
120
120
  if paused is not None:
121
121
  return paused
@@ -142,10 +142,12 @@ class DeepAgentsEngine:
142
142
  return self._runtime._outcome(RunStatus.MAX_STEPS, frame)
143
143
 
144
144
  self._record_steps(frame, models)
145
- paused = self._pause(frame, result, memory_key=memory_key, span=span)
145
+ paused = self._pause(frame, result, memory_key=memory_key, span=span, principal=principal)
146
146
  if paused is not None:
147
147
  return paused
148
- return await self._complete(frame, result, memory_key=memory_key, span=span)
148
+ return await self._complete(
149
+ frame, result, memory_key=memory_key, span=span, principal=principal
150
+ )
149
151
 
150
152
  # -- graph -------------------------------------------------------------------
151
153
 
@@ -410,7 +412,9 @@ class DeepAgentsEngine:
410
412
  )
411
413
  return calls
412
414
 
413
- def _pause(self, frame: _Frame, result: Any, *, memory_key: str, span: Span) -> _Outcome | None:
415
+ def _pause(
416
+ self, frame: _Frame, result: Any, *, memory_key: str, span: Span, principal: Principal
417
+ ) -> _Outcome | None:
414
418
  """Turn a held interrupt into our checkpoint, or ``None`` when nothing is held."""
415
419
  pending = result.get("__interrupt__")
416
420
  if not pending:
@@ -421,7 +425,7 @@ class DeepAgentsEngine:
421
425
  f"agent {frame.agent.id!r} paused on an interrupt that named no tool call; "
422
426
  "the harness's interrupt payload has changed shape"
423
427
  )
424
- checkpoint = self._runtime._checkpoint(frame, calls, memory_key)
428
+ checkpoint = self._runtime._checkpoint(frame, calls, memory_key, principal=principal)
425
429
  record_hitl(span, phase="pause", channel=checkpoint.channel, step=frame.step)
426
430
  self._runtime._record_status(span, "paused", frame)
427
431
  return _Outcome(
@@ -434,11 +438,17 @@ class DeepAgentsEngine:
434
438
  )
435
439
 
436
440
  async def _complete(
437
- self, frame: _Frame, result: Any, *, memory_key: str, span: Span
441
+ self,
442
+ frame: _Frame,
443
+ result: Any,
444
+ *,
445
+ memory_key: str,
446
+ span: Span,
447
+ principal: Principal,
438
448
  ) -> _Outcome:
439
449
  """Apply the output guardrail, record memory, and report the answer."""
440
450
  released = await self._runtime._guardrail_answer(
441
- frame, self._answer(result), memory_key, span=span
451
+ frame, self._answer(result), memory_key, span=span, principal=principal
442
452
  )
443
453
  if isinstance(released, _Outcome):
444
454
  return released
@@ -544,7 +554,11 @@ class _Guardrails(AgentMiddleware):
544
554
  return await self._delegate_in_span(request, handler, call)
545
555
  runtime._authorize(self._frame.agent, call, self._principal)
546
556
  guarded, halted = await runtime._guardrail_tool_calls(
547
- self._frame, [call], self._memory_key, span=self._record_span
557
+ self._frame,
558
+ [call],
559
+ self._memory_key,
560
+ span=self._record_span,
561
+ principal=self._principal,
548
562
  )
549
563
  if halted is not None:
550
564
  raise _HaltError(halted)
@@ -329,33 +329,35 @@ class AgentRuntime:
329
329
  principal: Principal | None = None,
330
330
  ) -> RunResult:
331
331
  """Continue a paused run from its checkpoint, with a human's answer."""
332
- checkpoint = await self._accept(checkpoint)
332
+ who = principal if principal is not None else Principal.unauthenticated()
333
+ # The principal is what the owner binding is checked against, so it is resolved
334
+ # before the checkpoint is read rather than threaded in afterwards.
335
+ checkpoint = await self._accept(checkpoint, who)
333
336
  resolved = HumanDecision(decision)
334
337
  self._restore_ledger(checkpoint)
335
338
  start_cost = self._gateway.ledger.cost_usd
336
339
  start_tokens = self._gateway.ledger.total_tokens
337
340
  try:
338
- outcome = await self._resume(
339
- checkpoint,
340
- resolved,
341
- principal if principal is not None else Principal.unauthenticated(),
342
- )
341
+ outcome = await self._resume(checkpoint, resolved, who)
343
342
  except BaseException:
344
343
  # Same rule as `run`: a resumed run that fails has been billed too.
345
344
  self._publish_spend(checkpoint.agent_id, start_cost, start_tokens)
346
345
  raise
347
346
  return self._wrap(outcome, start_cost, start_tokens)
348
347
 
349
- async def _accept(self, checkpoint: AgentCheckpoint) -> AgentCheckpoint:
348
+ async def _accept(self, checkpoint: AgentCheckpoint, principal: Principal) -> AgentCheckpoint:
350
349
  """Refuse a checkpoint this app did not issue, has expired, or already spent.
351
350
 
352
351
  Called before anything the checkpoint carries is read, so a tampered pending call
353
352
  is never authorized, priced or observed. A runtime built without a signer keeps the
354
353
  pre-signing behaviour, which is what a direct library embedder already had.
354
+
355
+ ``principal`` is what the checkpoint's owner binding is checked against: a run
356
+ paused by a principal with a subject can only be resumed by that same subject.
355
357
  """
356
358
  if self._signer is None:
357
359
  return checkpoint
358
- await self._signer.accept(checkpoint, self._nonces)
360
+ await self._signer.accept(checkpoint, self._nonces, subject=principal.subject)
359
361
  return checkpoint
360
362
 
361
363
  async def _resume(
@@ -510,7 +512,12 @@ class AgentRuntime:
510
512
  if not frame.input_checked:
511
513
  frame.input_checked = True
512
514
  paused = await self._guardrail_text(
513
- _GUARDRAIL_INPUT, frame, memory_key, span=span, rewrite=True
515
+ _GUARDRAIL_INPUT,
516
+ frame,
517
+ memory_key,
518
+ principal=principal,
519
+ span=span,
520
+ rewrite=True,
514
521
  )
515
522
  if paused is not None:
516
523
  return paused
@@ -533,7 +540,9 @@ class AgentRuntime:
533
540
  response = generation.response
534
541
 
535
542
  if not response.tool_calls:
536
- answer = await self._guardrail_answer(frame, response.text, memory_key, span=span)
543
+ answer = await self._guardrail_answer(
544
+ frame, response.text, memory_key, principal=principal, span=span
545
+ )
537
546
  if isinstance(answer, _Outcome):
538
547
  return answer
539
548
  frame.messages.append(Message.assistant(answer))
@@ -560,13 +569,13 @@ class AgentRuntime:
560
569
  record.kind = StepKind.TOOLS
561
570
  record.tool_names = tuple(call.name for call in response.tool_calls)
562
571
  guarded, paused = await self._guardrail_tool_calls(
563
- frame, response.tool_calls, memory_key, span=span
572
+ frame, response.tool_calls, memory_key, principal=principal, span=span
564
573
  )
565
574
  if paused is not None:
566
575
  return paused
567
576
  frame.messages.append(Message.assistant_tool_calls(response.text, guarded))
568
577
  if self._needs_approval(agent, guarded, principal):
569
- checkpoint = self._checkpoint(frame, guarded, memory_key)
578
+ checkpoint = self._checkpoint(frame, guarded, memory_key, principal=principal)
570
579
  record_hitl(
571
580
  span,
572
581
  phase="pause",
@@ -592,6 +601,7 @@ class AgentRuntime:
592
601
  frame: _Frame,
593
602
  memory_key: str,
594
603
  *,
604
+ principal: Principal,
595
605
  span: Span,
596
606
  rewrite: bool,
597
607
  ) -> _Outcome | None:
@@ -611,7 +621,9 @@ class AgentRuntime:
611
621
  if verdict.action == ACTION_BLOCK and deciding is not None:
612
622
  raise GuardrailBlockedError(deciding.guardrail, stage, deciding.message)
613
623
  if verdict.action == ACTION_ESCALATE:
614
- return self._guardrail_pause(frame, verdict, memory_key, (), span=span)
624
+ return self._guardrail_pause(
625
+ frame, verdict, memory_key, (), principal=principal, span=span
626
+ )
615
627
  if rewrite and verdict.action == ACTION_REDACT and index is not None:
616
628
  frame.messages[index] = Message.user(verdict.text)
617
629
  return None
@@ -622,6 +634,7 @@ class AgentRuntime:
622
634
  text: str,
623
635
  memory_key: str,
624
636
  *,
637
+ principal: Principal,
625
638
  span: Span,
626
639
  ) -> str | _Outcome:
627
640
  """Run the ``output`` stage over an answer, returning the text to ship.
@@ -638,7 +651,9 @@ class AgentRuntime:
638
651
  if verdict.action == ACTION_BLOCK and deciding is not None:
639
652
  raise GuardrailBlockedError(deciding.guardrail, _GUARDRAIL_OUTPUT, deciding.message)
640
653
  if verdict.action == ACTION_ESCALATE:
641
- return self._guardrail_pause(frame, verdict, memory_key, (), span=span, text=text)
654
+ return self._guardrail_pause(
655
+ frame, verdict, memory_key, (), principal=principal, span=span, text=text
656
+ )
642
657
  return verdict.text if verdict.action == ACTION_REDACT else text
643
658
 
644
659
  async def _guardrail_tool_calls(
@@ -647,6 +662,7 @@ class AgentRuntime:
647
662
  calls: Sequence[ToolCall],
648
663
  memory_key: str,
649
664
  *,
665
+ principal: Principal,
650
666
  span: Span,
651
667
  ) -> tuple[list[ToolCall], _Outcome | None]:
652
668
  """Run the ``tool-call`` stage over every call in one step.
@@ -675,7 +691,9 @@ class AgentRuntime:
675
691
  call = call.model_copy(update={"arguments": dict(verdict.arguments)})
676
692
  guarded.append(call)
677
693
  if escalation is not None:
678
- return guarded, self._guardrail_pause(frame, escalation, memory_key, guarded, span=span)
694
+ return guarded, self._guardrail_pause(
695
+ frame, escalation, memory_key, guarded, principal=principal, span=span
696
+ )
679
697
  return guarded, None
680
698
 
681
699
  def _record_guardrails(self, frame: _Frame, verdict: GuardrailVerdict, span: Span) -> None:
@@ -691,6 +709,7 @@ class AgentRuntime:
691
709
  memory_key: str,
692
710
  calls: Sequence[ToolCall],
693
711
  *,
712
+ principal: Principal,
694
713
  span: Span,
695
714
  text: str = "",
696
715
  ) -> _Outcome:
@@ -708,7 +727,9 @@ class AgentRuntime:
708
727
  channel=approval.channel if approval is not None else _GUARDRAIL_CHANNEL,
709
728
  text=text,
710
729
  )
711
- checkpoint = self._checkpoint(frame, calls, memory_key, escalation=escalation)
730
+ checkpoint = self._checkpoint(
731
+ frame, calls, memory_key, principal=principal, escalation=escalation
732
+ )
712
733
  record_hitl(
713
734
  span,
714
735
  phase="pause",
@@ -835,9 +856,9 @@ class AgentRuntime:
835
856
  inner.steps = [*frame.steps, *inner.steps]
836
857
  inner.guardrails = (*frame.guardrails, *inner.guardrails)
837
858
  if inner.checkpoint is not None:
838
- caller = self._checkpoint(frame, (call,), memory_key).model_copy(
839
- update={"resume_kind": "delegate", "channel": ""}
840
- )
859
+ caller = self._checkpoint(
860
+ frame, (call,), memory_key, principal=principal
861
+ ).model_copy(update={"resume_kind": "delegate", "channel": ""})
841
862
  inner.checkpoint = inner.checkpoint.model_copy(update={"caller": caller})
842
863
  return inner
843
864
  if inner.status is not RunStatus.COMPLETED:
@@ -1114,6 +1135,7 @@ class AgentRuntime:
1114
1135
  calls: Sequence[ToolCall],
1115
1136
  memory_key: str,
1116
1137
  *,
1138
+ principal: Principal,
1117
1139
  escalation: GuardrailEscalation | None = None,
1118
1140
  ) -> AgentCheckpoint:
1119
1141
  approval = frame.agent.approval
@@ -1145,7 +1167,12 @@ class AgentRuntime:
1145
1167
  # Signed here rather than at the route, so every pause path -- approval, tool
1146
1168
  # confirmation, guardrail escalation, and the nested caller of a delegate -- is
1147
1169
  # issued by the same key. A second signing site is a second thing to forget.
1148
- return checkpoint if self._signer is None else self._signer.sign(checkpoint)
1170
+ # The principal travels with it for the same reason: the subject that paused the
1171
+ # run is only available here, and a pause that skipped the binding would hand out
1172
+ # a checkpoint anyone holding it could resume.
1173
+ if self._signer is None:
1174
+ return checkpoint
1175
+ return self._signer.sign(checkpoint, subject=principal.subject)
1149
1176
 
1150
1177
  def _restore_ledger(self, checkpoint: AgentCheckpoint) -> None:
1151
1178
  """Carry a pause's spend into this process's ledger before resuming.
@@ -47,6 +47,12 @@ class Principal:
47
47
  roles: frozenset[str] = frozenset()
48
48
  scopes: frozenset[str] = frozenset()
49
49
  authenticated: bool = False
50
+ # A stable identifier for the caller as their token issuer named them -- a `sub`
51
+ # claim, a service-account id. It is *not* derived from ``authenticated``: a
52
+ # principal can be authenticated without a subject, and a checkpoint paused by one
53
+ # is therefore not owner-bound. Only this field binds a checkpoint to a person, so
54
+ # an app that verifies tokens should set it from the verified claim.
55
+ subject: str | None = None
50
56
 
51
57
  @classmethod
52
58
  def unauthenticated(cls) -> Principal:
@@ -7,20 +7,37 @@ holding one could edit an approval decision or swap the pending tool-call argume
7
7
  the loop would execute the edited call. A signature is what turns "a body shaped like a
8
8
  checkpoint" into "a checkpoint this app issued".
9
9
 
10
- Three properties are enforced here, and each has its own refusal reason:
10
+ Four properties are enforced here, and each has its own refusal reason:
11
11
 
12
12
  * ``"tampered"`` -- the HMAC does not match the payload the signer covered. The signature
13
13
  covers the *whole* checkpoint minus the signature itself, so a flipped approval
14
14
  decision, a swapped argument and an extended expiry all fail the same check rather than
15
15
  needing a field-by-field audit.
16
16
  * ``"expired"`` -- ``expires_at`` (inside the signed payload, so it cannot be extended
17
- without breaking the signature) is in the past.
17
+ without breaking the signature) is in the past, allowing ``leeway_seconds`` of clock
18
+ skew between the host that paused and the host that resumes.
19
+ * ``"unbound"`` -- the checkpoint was issued to a named principal and this caller is not
20
+ that principal, or the caller presents no subject at all. The owner is a keyed hash of
21
+ the principal's ``subject`` inside the signed payload, so it cannot be stripped or
22
+ rewritten, only presented correctly.
18
23
  * ``"replayed"`` -- the nonce was already claimed. Claiming is a store operation rather
19
24
  than an in-memory check because a replay across two processes is the interesting case.
20
25
 
26
+ Signing and owner binding are domain-separated: the same secret derives the checkpoint
27
+ MAC and the owner hash through different prefixes, so a value from one use can never be
28
+ presented as the other. The prefix is versioned (``aid.checkpoint.v2``) because changing
29
+ it is how a payload-format change invalidates in-flight checkpoints instead of silently
30
+ reinterpreting them.
31
+
21
32
  The secret is a *value read from the environment*, never a value in the spec: the
22
33
  generated app names the variable and this module fails loudly when it is unset, because a
23
- missing secret must not degrade into "unsigned".
34
+ missing secret must not degrade into "unsigned". A secret shorter than
35
+ :data:`MIN_SECRET_BYTES` is refused for the same reason a missing one is -- it looks set
36
+ and is not.
37
+
38
+ Refusal reasons are for the log, not the wire. The generated route answers every refusal
39
+ with one opaque 403, because the difference between "expired" and "tampered" is useful to
40
+ an operator and an oracle to an unauthenticated caller holding a guessed checkpoint.
24
41
 
25
42
  Replay durability is limited by the nonce store, and that limit is real rather than
26
43
  theoretical: :class:`InProcessNonceStore` forgets on restart and does not span replicas.
@@ -53,6 +70,8 @@ from aid_runtime.errors import AidRuntimeError, ConfigurationError
53
70
 
54
71
  __all__ = [
55
72
  "DEFAULT_CHECKPOINT_TTL_MINUTES",
73
+ "DEFAULT_CLOCK_LEEWAY_SECONDS",
74
+ "MIN_SECRET_BYTES",
56
75
  "CheckpointRefusalError",
57
76
  "CheckpointSigner",
58
77
  "InProcessNonceStore",
@@ -68,14 +87,45 @@ __all__ = [
68
87
  #: a person in the same change window, not a durable queue.
69
88
  DEFAULT_CHECKPOINT_TTL_MINUTES = 15
70
89
 
90
+ #: Tolerance for a clock difference between the host that paused and the host that
91
+ #: resumes. A pause is verified on whichever replica serves the resume request, so the two
92
+ #: clocks are not guaranteed equal; without this, a checkpoint could be refused as expired
93
+ #: by a replica that is seconds ahead. It widens the expiry by this much and no more.
94
+ DEFAULT_CLOCK_LEEWAY_SECONDS = 30
95
+
96
+ #: The shortest secret this module will sign with, in UTF-8 bytes. A 32-byte key is the
97
+ #: output size of SHA-256, so a shorter one caps the strength of the MAC below its own
98
+ #: hash. A secret that is set but weak is worse than one that is missing, because a
99
+ #: missing one is loud and a weak one looks configured.
100
+ MIN_SECRET_BYTES = 32
101
+
102
+ #: Domain separators. Prepended to the bytes each use signs, so the checkpoint MAC and the
103
+ #: owner hash can never be confused for one another even under one shared secret. The
104
+ #: ``v2`` suffix is the payload format version: bumping it is how a format change
105
+ #: invalidates in-flight checkpoints rather than reinterpreting them under new rules.
106
+ _CHECKPOINT_DOMAIN = b"aid.checkpoint.v2\x00"
107
+ _OWNER_DOMAIN = b"aid.checkpoint.owner.v2\x00"
108
+
109
+
110
+ def _same(expected: str, presented: str) -> bool:
111
+ """Constant-time comparison of a computed hex digest against an untrusted string.
112
+
113
+ Both sides are encoded before comparison. ``hmac.compare_digest`` refuses two ``str``
114
+ arguments that contain non-ASCII characters, so comparing the decoded strings would
115
+ turn a malicious checkpoint carrying a non-ASCII ``signature`` into a ``TypeError`` --
116
+ a 500 for what is simply a bad signature. Comparing bytes makes any presented value
117
+ comparable and therefore simply unequal.
118
+ """
119
+ return hmac.compare_digest(expected.encode("ascii"), presented.encode("utf-8"))
120
+
71
121
 
72
122
  class CheckpointRefusalError(AidRuntimeError):
73
123
  """A resume body this app will not honour, with a stable machine-readable reason.
74
124
 
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.
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.
79
129
  """
80
130
 
81
131
  def __init__(self, reason: str, message: str) -> None:
@@ -215,21 +265,41 @@ def checkpoint_payload(checkpoint: AgentCheckpoint) -> bytes:
215
265
  """The canonical bytes a signature covers.
216
266
 
217
267
  Everything except the signature itself. That includes the integrity block's own
218
- ``issued_at``, ``expires_at`` and ``nonce``: leaving those out would let a holder
219
- move their deadline forward, and would let them swap the nonce of an already-spent
220
- checkpoint to walk past replay protection. The pending calls, the approval channel
221
- and the nested ``caller`` frames are inside too, so one signature binds all of them.
222
- Sorted keys and no separator padding make the encoding reproducible in a second
223
- process, which a signature requires.
268
+ ``issued_at``, ``expires_at``, ``owner`` and ``nonce``: leaving those out would let a
269
+ holder move their deadline forward or rebind the checkpoint to themselves, and would
270
+ let them swap the nonce of an already-spent checkpoint to walk past replay protection.
271
+ The pending calls, the approval channel and the nested ``caller`` frames are inside
272
+ too, so one signature binds all of them. Sorted keys and no separator padding make the
273
+ encoding reproducible in a second process, which a signature requires.
274
+
275
+ There is deliberately no ``default=`` fallback for a value JSON cannot represent. A
276
+ fallback stringifies it, and two different values that stringify alike would produce
277
+ the same payload for different checkpoints -- a collision in the thing being signed.
278
+ A checkpoint that cannot be encoded is refused instead, and the model's own strictness
279
+ is what should have stopped it reaching here.
280
+
281
+ The dump runs in JSON mode before this function, so a value pydantic can *normalise*
282
+ is normalised rather than refused: a ``NaN`` in ``when`` reaches the encoder as
283
+ ``null``. That is not the same as the fallback above, because the loop never
284
+ interprets such a value -- the two forms are the same checkpoint to every reader,
285
+ rather than two checkpoints the signature cannot tell apart.
224
286
  """
225
- document = checkpoint.model_dump(mode="json", exclude={"integrity": {"signature"}})
226
- return json.dumps(
227
- document,
228
- sort_keys=True,
229
- separators=(",", ":"),
230
- ensure_ascii=False,
231
- default=str,
232
- ).encode("utf-8")
287
+ try:
288
+ document = checkpoint.model_dump(mode="json", exclude={"integrity": {"signature"}})
289
+ encoded = json.dumps(
290
+ document,
291
+ sort_keys=True,
292
+ separators=(",", ":"),
293
+ ensure_ascii=False,
294
+ allow_nan=False,
295
+ )
296
+ except (TypeError, ValueError) as error:
297
+ raise ConfigurationError(
298
+ f"a checkpoint for agent {checkpoint.agent_id!r} cannot be signed because its "
299
+ f"payload is not canonical JSON ({error}); a value the encoder has to guess at "
300
+ "is a value a signature cannot bind"
301
+ ) from error
302
+ return encoded.encode("utf-8")
233
303
 
234
304
 
235
305
  @dataclass(frozen=True, slots=True)
@@ -239,41 +309,87 @@ class CheckpointSigner:
239
309
  ``secret`` is read from the environment by the caller; it is never a spec value. The
240
310
  dataclass is frozen and holds no mutable state, so one instance can be shared across
241
311
  requests and a test can construct its own without touching the process environment.
312
+
313
+ ``previous`` is the secret being rotated out. It is accepted for verification only, so
314
+ a checkpoint issued before a rotation still resumes; it never signs. Rotation is
315
+ bounded by the checkpoint TTL rather than by this field: a checkpoint lives for
316
+ ``ttl_seconds``, so a retired secret is worth keeping for exactly that long and no
317
+ longer, and dropping it after that is what makes the rotation a rotation rather than a
318
+ permanent second key.
242
319
  """
243
320
 
244
321
  secret: str = field(repr=False)
245
322
  ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
323
+ previous: str | None = field(default=None, repr=False)
324
+ leeway_seconds: int = DEFAULT_CLOCK_LEEWAY_SECONDS
246
325
 
247
326
  def __post_init__(self) -> None:
248
- if not self.secret:
327
+ for name, value in (("secret", self.secret), ("previous", self.previous)):
328
+ if value is None:
329
+ continue
330
+ if not value:
331
+ raise ValueError(
332
+ f"CheckpointSigner needs a non-empty {name}; an empty key would sign "
333
+ "every checkpoint identically"
334
+ )
335
+ size = len(value.encode("utf-8"))
336
+ if size < MIN_SECRET_BYTES:
337
+ raise ValueError(
338
+ f"CheckpointSigner needs a {name} of at least {MIN_SECRET_BYTES} "
339
+ f"bytes; this one is {size}. A key shorter than the hash it feeds "
340
+ "lowers the strength of every signature it makes"
341
+ )
342
+ if self.previous is not None and self.previous == self.secret:
249
343
  raise ValueError(
250
- "CheckpointSigner needs a non-empty secret; an empty key would sign "
251
- "every checkpoint identically"
344
+ "CheckpointSigner was given the same value for secret and previous; a "
345
+ "rotation has to name two different keys, or it has rotated nothing"
252
346
  )
253
347
  if self.ttl_seconds <= 0:
254
348
  raise ValueError("CheckpointSigner needs a positive ttl_seconds")
349
+ if self.leeway_seconds < 0:
350
+ raise ValueError("CheckpointSigner needs a non-negative leeway_seconds")
255
351
 
256
- def _mac(self, payload: bytes) -> str:
257
- return hmac.new(self.secret.encode("utf-8"), payload, hashlib.sha256).hexdigest()
352
+ @staticmethod
353
+ def _mac(key: bytes, domain: bytes, payload: bytes) -> str:
354
+ return hmac.new(key, domain + payload, hashlib.sha256).hexdigest()
258
355
 
259
- def _digest(self, checkpoint: AgentCheckpoint) -> str:
356
+ def _digest(self, checkpoint: AgentCheckpoint, key: bytes | None = None) -> str:
260
357
  """The MAC of ``checkpoint`` excluding only the signature field.
261
358
 
262
359
  Signing and verifying both go through here, so the two sides cannot drift into
263
360
  covering different bytes: a signature that verifies against a payload it was not
264
361
  computed over would accept an edited checkpoint.
265
362
  """
266
- return self._mac(checkpoint_payload(checkpoint))
363
+ material = self.secret.encode("utf-8") if key is None else key
364
+ return self._mac(material, _CHECKPOINT_DOMAIN, checkpoint_payload(checkpoint))
365
+
366
+ @staticmethod
367
+ def owner_of(subject: str | None, *, key: bytes) -> str:
368
+ """The keyed hash a checkpoint carries for ``subject``, or ``""`` for none.
369
+
370
+ A keyed hash rather than the subject itself: the checkpoint body travels through
371
+ the caller, so writing a user id into it would hand every holder an identifier
372
+ they did not already have. The key is what makes the hash unguessable, and the
373
+ domain is what keeps it from ever equalling a signature.
374
+ """
375
+ if not subject:
376
+ return ""
377
+ return CheckpointSigner._mac(key, _OWNER_DOMAIN, subject.encode("utf-8"))
267
378
 
268
379
  def sign(
269
380
  self,
270
381
  checkpoint: AgentCheckpoint,
271
382
  *,
383
+ subject: str | None = None,
272
384
  now: int | None = None,
273
385
  nonce: str | None = None,
274
386
  ) -> AgentCheckpoint:
275
387
  """Return a copy of ``checkpoint`` carrying a fresh integrity block.
276
388
 
389
+ ``subject`` is the verified identity of the principal pausing the run. When it is
390
+ absent the checkpoint is signed but unbound, which is the honest result for a
391
+ principal that carries no subject: there is nothing to bind to.
392
+
277
393
  ``now`` and ``nonce`` exist for tests; production passes neither. The return is a
278
394
  new frozen model, so a caller that kept the unsigned value still has it.
279
395
  """
@@ -282,6 +398,7 @@ class CheckpointSigner:
282
398
  issued_at=issued_at,
283
399
  expires_at=issued_at + self.ttl_seconds,
284
400
  nonce=secrets.token_urlsafe(24) if nonce is None else nonce,
401
+ owner=self.owner_of(subject, key=self.secret.encode("utf-8")),
285
402
  signature="",
286
403
  )
287
404
  unsigned = checkpoint.model_copy(update={"integrity": integrity})
@@ -290,8 +407,14 @@ class CheckpointSigner:
290
407
  update={"integrity": integrity.model_copy(update={"signature": signature})}
291
408
  )
292
409
 
293
- def verify(self, checkpoint: AgentCheckpoint, *, now: int | None = None) -> CheckpointIntegrity:
294
- """Check signature and expiry. Returns the integrity block, or raises.
410
+ def verify(
411
+ self,
412
+ checkpoint: AgentCheckpoint,
413
+ *,
414
+ subject: str | None = None,
415
+ now: int | None = None,
416
+ ) -> CheckpointIntegrity:
417
+ """Check signature, expiry and owner binding. Returns the block, or raises.
295
418
 
296
419
  Replay is *not* checked here: it needs the store, and therefore an ``await``.
297
420
  :meth:`accept` is the full check a request handler wants.
@@ -303,32 +426,65 @@ class CheckpointSigner:
303
426
  "this checkpoint carries no signature, so it was not issued by an app "
304
427
  "built with checkpoint signing",
305
428
  )
306
- expected = self._digest(checkpoint)
307
- if not hmac.compare_digest(expected, integrity.signature):
308
- raise CheckpointRefusalError(
309
- "tampered",
310
- "this checkpoint's signature does not match its contents; it was edited "
311
- "after it was issued",
312
- )
429
+ key = self._verifying_key(checkpoint, integrity)
313
430
  moment = int(time.time()) if now is None else int(now)
314
- if integrity.expires_at <= moment:
431
+ if integrity.expires_at + self.leeway_seconds <= moment:
315
432
  raise CheckpointRefusalError(
316
433
  "expired",
317
434
  f"this checkpoint expired at {integrity.expires_at}; a pause is valid for "
318
435
  f"{self.ttl_seconds} seconds, so resume it sooner or start the run again",
319
436
  )
437
+ if integrity.owner:
438
+ # The owner hash was derived from whichever key signed this checkpoint, so it
439
+ # is recomputed with that same key: after a rotation the current secret would
440
+ # produce a hash that never matches a checkpoint the previous one issued.
441
+ if not subject:
442
+ raise CheckpointRefusalError(
443
+ "unbound",
444
+ "this checkpoint was issued to a named principal, and the caller "
445
+ "presented no subject, so there is no identity to check it against",
446
+ )
447
+ expected_owner = self.owner_of(subject, key=key)
448
+ if not _same(expected_owner, integrity.owner):
449
+ raise CheckpointRefusalError(
450
+ "unbound",
451
+ "this checkpoint was issued to a different principal; a resume is "
452
+ "accepted only from the caller who paused the run",
453
+ )
320
454
  return integrity
321
455
 
456
+ def _verifying_key(self, checkpoint: AgentCheckpoint, integrity: CheckpointIntegrity) -> bytes:
457
+ """The key this checkpoint's signature verifies under, or a refusal.
458
+
459
+ The current secret is tried first and the retired one second, so a rotation takes
460
+ effect immediately for new checkpoints and stays compatible for the TTL of the old
461
+ ones. Both attempts go through the same comparison, so which key matched is not
462
+ something a caller can observe.
463
+ """
464
+ current = self.secret.encode("utf-8")
465
+ if _same(self._digest(checkpoint, current), integrity.signature):
466
+ return current
467
+ if self.previous is not None:
468
+ retired = self.previous.encode("utf-8")
469
+ if _same(self._digest(checkpoint, retired), integrity.signature):
470
+ return retired
471
+ raise CheckpointRefusalError(
472
+ "tampered",
473
+ "this checkpoint's signature does not match its contents; it was edited "
474
+ "after it was issued",
475
+ )
476
+
322
477
  async def accept(
323
478
  self,
324
479
  checkpoint: AgentCheckpoint,
325
480
  nonces: NonceStore,
326
481
  *,
482
+ subject: str | None = None,
327
483
  now: int | None = None,
328
484
  ) -> CheckpointIntegrity:
329
- """Signature, then expiry, then a one-time claim. Raises on any failure."""
485
+ """Signature, then expiry, then owner, then a one-time claim. Raises on failure."""
330
486
  moment = int(time.time()) if now is None else int(now)
331
- integrity = self.verify(checkpoint, now=moment)
487
+ integrity = self.verify(checkpoint, subject=subject, now=moment)
332
488
  claimed = await nonces.claim(
333
489
  nonce=integrity.nonce, expires_at=integrity.expires_at, now=moment
334
490
  )
@@ -344,14 +500,24 @@ class CheckpointSigner:
344
500
  def signer_from_env(
345
501
  variable: str, *, ttl_seconds: int = DEFAULT_CHECKPOINT_TTL_MINUTES * 60
346
502
  ) -> CheckpointSigner:
347
- """Build a signer from ``os.environ[variable]``, naming the variable when it is unset."""
503
+ """Build a signer from ``os.environ[variable]``, naming the variable when it is unset.
504
+
505
+ ``{variable}_PREVIOUS`` is read as the secret being rotated out, when it is set. A
506
+ rotation is therefore a deployment in two steps -- set ``_PREVIOUS`` to the old value
507
+ and the variable to the new one, then unset ``_PREVIOUS`` once the checkpoint TTL has
508
+ passed -- and neither step requires downtime.
509
+ """
348
510
  secret = os.environ.get(variable, "")
349
511
  if not secret:
350
512
  raise ConfigurationError(
351
513
  f"{variable} is not set, but this app signs its checkpoints; set it to a "
352
514
  "high-entropy secret before serving the resume route"
353
515
  )
354
- return CheckpointSigner(secret=secret, ttl_seconds=ttl_seconds)
516
+ previous = os.environ.get(f"{variable}_PREVIOUS", "") or None
517
+ try:
518
+ return CheckpointSigner(secret=secret, ttl_seconds=ttl_seconds, previous=previous)
519
+ except ValueError as error:
520
+ raise ConfigurationError(f"{variable}: {error}") from error
355
521
 
356
522
 
357
523
  def nonce_store_for(kind: str | None, location: str | None) -> NonceStore:
@@ -95,6 +95,12 @@ class CheckpointIntegrity(BaseModel):
95
95
  without breaking the signature and ``nonce`` cannot be swapped to replay a spent
96
96
  checkpoint under a fresh identity. The signature itself does not cover itself.
97
97
 
98
+ ``owner`` binds the checkpoint to the principal that paused it: a keyed hash of the
99
+ caller's ``subject``, computed by the signer rather than sent by the caller. Empty
100
+ means the pause was made by a principal with no subject, which is the honest state
101
+ of an app that has not integrated token verification -- such a checkpoint stays a
102
+ bearer capability, and ``ir/resume-owner-unbound`` is what says so at build time.
103
+
98
104
  Absent on a runtime built without a signer (a library embedding the loop directly);
99
105
  the generated app always passes one, so an HTTP checkpoint is never unsigned.
100
106
  """
@@ -104,6 +110,7 @@ class CheckpointIntegrity(BaseModel):
104
110
  issued_at: int = Field(ge=0)
105
111
  expires_at: int = Field(ge=0)
106
112
  nonce: str = Field(min_length=1)
113
+ owner: str = ""
107
114
  signature: str = ""
108
115
 
109
116
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.176
3
+ Version: 0.1.177
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=Lz8AUsJcP12yPAZmTY64U7pw8qDh-toNYPmx5dKudHw,15277
1
+ aid_runtime/__init__.py,sha256=vIojrTw1G1B-OwvDKymHQglCh4P0Otg8VtuIyPRVByc,15277
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,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=rf3k0hxHDO60S1TrON6d2-rTv1N8V4WvF47xsJ5bhE0,3709
21
+ aid_runtime/agents/__init__.py,sha256=ErdKuLaHi0rfN4Z3IE0akevF7W6-RH4F-i7LxCqziDE,3825
22
22
  aid_runtime/agents/chat_model.py,sha256=RHMA3_Yb8UE14YQo8k-ylUZiQnOvUKDnl1AEKBG_rgU,16526
23
- aid_runtime/agents/deep_agents.py,sha256=ArNm1MGDgsrO5AKkin0WYzDhGcMM7Q0XO0wi8qFUT5o,27338
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=fKT5iemOqoOuSXw_zbu-BxJzDdWqyBZqcZZFcfG1h_g,59587
27
+ aid_runtime/agents/loop.py,sha256=WVQZd7XWmjGC1c5DE9M-OQd90REKvuYlyiqsRYtT_YY,60809
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=IbJ9LQDPOumwup5K_eeyFAfCLFuMqEK6iSvBrM6o16Q,6610
31
- aid_runtime/agents/resume.py,sha256=vpCwC2lLMVOyrg4N3D0l1CSqRi57uongjpBpDlLQkrs,17294
32
- aid_runtime/agents/state.py,sha256=feXZtQeD3vcKpNUPsCXby0J15UqkoD4_Gi-aT3Up8RI,7174
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
33
33
  aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
34
34
  aid_runtime/evals/agent_runner.py,sha256=sffFGqZDBLmKkce6t82IaWJLHNq-q7HuSmIM61uEkoU,13513
35
35
  aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
@@ -63,7 +63,7 @@ aid_runtime/retrieval/rerank.py,sha256=L4ICBi9YHDzhnKVtImKh5Wzre1HDzS8at-AKDkXBJ
63
63
  aid_runtime/retrieval/retriever.py,sha256=0Cx-_6Qcf2TRolFy4ktMseyyyr-WLphMYYHane0t9lA,24412
64
64
  aid_runtime/retrieval/stores.py,sha256=mG261rUHZIzB7niiTj_DuUzcNMOd4QYENk5ArgI1iBo,6840
65
65
  aid_runtime/retrieval/types.py,sha256=hJ5IRSD-PTfrc1xhuK6CBdX0Yr-S6L_JeSMPity8ecM,20447
66
- aid_runtime_python-0.1.176.dist-info/METADATA,sha256=f9_7fKxRA22Ykbb0p3OHLACjdp33qFJ49Mri0Ax7sF8,17163
67
- aid_runtime_python-0.1.176.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
- aid_runtime_python-0.1.176.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
- aid_runtime_python-0.1.176.dist-info/RECORD,,
66
+ aid_runtime_python-0.1.177.dist-info/METADATA,sha256=1R10uTnJyvicBzqMFik_nV8lIZQ4VfneD-HI0-haGAo,17163
67
+ aid_runtime_python-0.1.177.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
+ aid_runtime_python-0.1.177.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
+ aid_runtime_python-0.1.177.dist-info/RECORD,,