aid-runtime-python 0.1.163__py3-none-any.whl → 0.1.165__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
@@ -207,7 +207,7 @@ from aid_runtime.providers import (
207
207
  default_bedrock_base_url,
208
208
  default_vertex_base_url,
209
209
  )
210
- from aid_runtime.redaction import REDACTED_FORMAT, redact_values
210
+ from aid_runtime.redaction import REDACTED_FORMAT, bind_redactions, redact_values
211
211
  from aid_runtime.retrieval import (
212
212
  DEFAULT_CANDIDATE_FACTOR,
213
213
  DEFAULT_SYNC_TIMEOUT_SECONDS,
@@ -356,7 +356,7 @@ from aid_runtime.types import (
356
356
  )
357
357
 
358
358
  #: Kept in sync with ``pyproject.toml`` by a test, so the two cannot drift.
359
- __version__ = "0.1.163"
359
+ __version__ = "0.1.165"
360
360
 
361
361
  __all__ = [
362
362
  "AGENT_LABEL",
@@ -596,6 +596,7 @@ __all__ = [
596
596
  "agent_span",
597
597
  "aid_attributes",
598
598
  "assemble_context",
599
+ "bind_redactions",
599
600
  "binding_from_managed_spec",
600
601
  "binding_from_spec",
601
602
  "bm25_scores",
@@ -51,6 +51,7 @@ from pydantic import Field
51
51
  from aid_runtime.cost import Budget
52
52
  from aid_runtime.errors import DeepAgentsEngineError, DeepAgentsMaxStepsError
53
53
  from aid_runtime.gateway import ModelGateway
54
+ from aid_runtime.redaction import bind_redactions
54
55
  from aid_runtime.types import CompletionRequest, Message, ToolCall, ToolDefinition
55
56
 
56
57
  __all__ = [
@@ -80,6 +81,14 @@ class GatewayChatModel(BaseChatModel):
80
81
  #: harness's own limiter completes the run with a synthetic answer instead of
81
82
  #: failing. ``None`` disables the counter (used by the offline fixtures).
82
83
  max_calls: int | None = None
84
+ #: ``observability.redact``: the fields the recorded copy of each generation must
85
+ #: not carry. The harness hands this adapter a conversation, not a render, so the
86
+ #: values are bound from the tool calls in that conversation -- the same source the
87
+ #: native loop uses.
88
+ redact: tuple[str, ...] = ()
89
+ #: The ``(name, value)`` pairs learned so far. Kept because the harness may trim the
90
+ #: conversation it hands back, and a value learned once stays withheld.
91
+ redactions: tuple[tuple[str, str], ...] = ()
83
92
  #: What ``bind_tools`` last admitted. Read by tests, never by the harness.
84
93
  bound_tools: tuple[ToolDefinition, ...] = ()
85
94
  #: Every generation this model produced, in order. The proof that the harness
@@ -125,6 +134,28 @@ class GatewayChatModel(BaseChatModel):
125
134
  "accounting path. Use ainvoke."
126
135
  )
127
136
 
137
+ def _withhold(self, conversation: Sequence[Message]) -> tuple[tuple[str, str], ...]:
138
+ """Learn what to withhold from the tool calls the harness handed back.
139
+
140
+ Called before every generation, so a value that entered the conversation one
141
+ call ago is withheld from the moment it appears. Only declared field names are
142
+ bound and only string values -- the same rule as the native loop, and it carries
143
+ the same limit: a value the model mentions in free text has no field name to
144
+ match, so ``observability.redact`` cannot reach it.
145
+ """
146
+ if not self.redact:
147
+ return ()
148
+ known = list(self.redactions)
149
+ for message in conversation:
150
+ for call in message.tool_calls:
151
+ for pair in bind_redactions(self.redact, call.arguments):
152
+ if pair not in known:
153
+ known.append(pair)
154
+ learned = tuple(known)
155
+ if learned != self.redactions:
156
+ self.redactions = learned
157
+ return learned
158
+
128
159
  async def _agenerate(
129
160
  self,
130
161
  messages: list[BaseMessage],
@@ -139,9 +170,11 @@ class GatewayChatModel(BaseChatModel):
139
170
  breach is raised, not returned: the harness must not be able to continue
140
171
  past a budget the ledger already refused.
141
172
  """
173
+ conversation = to_aid_messages(messages)
142
174
  request = CompletionRequest(
143
- messages=to_aid_messages(messages),
175
+ messages=conversation,
144
176
  tools=self.bound_tools,
177
+ redactions=self._withhold(conversation),
145
178
  )
146
179
  if self.max_calls is not None and len(self.calls) >= self.max_calls:
147
180
  # Refused before the call, not after: an agent that has spent its step
@@ -225,6 +225,7 @@ class DeepAgentsEngine:
225
225
  budget=budget,
226
226
  allowed_tools=frozenset(allowed),
227
227
  max_calls=max(agent.max_steps - frame.step, 0),
228
+ redact=self._runtime.spec.redact,
228
229
  )
229
230
  models.append((agent.id, model))
230
231
  return model
@@ -311,12 +312,18 @@ class DeepAgentsEngine:
311
312
  definition = self._runtime._executor.definition(spec.name)
312
313
 
313
314
  async def _call(
314
- _agent: AgentDefinition = agent, _name: str = spec.name, **kwargs: Any
315
+ _agent: AgentDefinition = agent,
316
+ _name: str = spec.name,
317
+ _frame: _Frame = frame,
318
+ **kwargs: Any,
315
319
  ) -> str:
316
320
  # The id is derived, not random: the harness pairs a result with its
317
321
  # call by id, and a random one would make two identical runs differ.
318
322
  call = ToolCall(id=f"{_agent.id}:{_name}", name=_name, arguments=kwargs)
319
- observations = await self._runtime._observe(_agent, [call], principal)
323
+ # The run's frame, so the value a tool call carries is bound for
324
+ # redaction exactly as it is under the native engine; `agent` keeps
325
+ # the delegate's own grant in force for a delegated call.
326
+ observations = await self._runtime._observe(_frame, [call], principal, agent=_agent)
320
327
  return observations[0].content
321
328
 
322
329
  tools.append(
aid_runtime/agents/ir.py CHANGED
@@ -260,6 +260,13 @@ class RuntimeSpec:
260
260
  #: ``None`` means unbounded: the runtime only shares a limiter when a deployment
261
261
  #: declares one, which keeps plain request/response usage free of surprises.
262
262
  concurrency: int | None = None
263
+ #: ``observability.redact``: the fields a recorded trace must not carry. A pipeline
264
+ #: binds them when it renders a prompt; the loop binds them from the structured
265
+ #: records it handles (tool-call arguments) and from any the caller supplies, and
266
+ #: the gateway strips them from the copy it writes. An agent run has no render, so
267
+ #: a value that appears only in free text is not bound -- the limit is documented
268
+ #: where the declaration is.
269
+ redact: tuple[str, ...] = ()
263
270
 
264
271
  def agent(self, agent_id: str) -> AgentDefinition:
265
272
  try:
@@ -365,6 +372,7 @@ def from_ir(document: Mapping[str, Any]) -> RuntimeSpec:
365
372
  guardrails=guardrails,
366
373
  decisions=decisions,
367
374
  concurrency=_concurrency(document.get("deployments")),
375
+ redact=_document_redact(document),
368
376
  )
369
377
 
370
378
 
@@ -760,6 +768,20 @@ def _concurrency(raw: Any) -> int | None:
760
768
  return max(declared) if declared else None
761
769
 
762
770
 
771
+ def _document_redact(document: Mapping[str, Any]) -> tuple[str, ...]:
772
+ """``observability.redact``, the fields a recorded trace must not carry.
773
+
774
+ Read rather than re-derived: the IR already lowered the set, including the fields
775
+ its sensitive-name rule added, and a second derivation here would be a policy the
776
+ gates never saw. An absent block is an empty set, not an error -- the runtime runs
777
+ documents the shipped templates emit, and they declare nothing to withhold.
778
+ """
779
+ observability = document.get("observability")
780
+ if not isinstance(observability, Mapping):
781
+ return ()
782
+ return tuple(_str_list(observability.get("redact"), "observability.redact"))
783
+
784
+
763
785
  def _memory(memory_id: str, entry: Mapping[str, Any]) -> MemoryDefinition:
764
786
  where = f"memory {memory_id!r}"
765
787
  token_budget = entry.get("tokenBudget")
@@ -96,6 +96,7 @@ from aid_runtime.errors import (
96
96
  from aid_runtime.gateway import ModelGateway
97
97
  from aid_runtime.metrics import record_agent_run
98
98
  from aid_runtime.providers.base import Provider
99
+ from aid_runtime.redaction import Redaction, bind_redactions
99
100
  from aid_runtime.tools import Tool, ToolExecutor
100
101
  from aid_runtime.tracing import agent_span, record_attributes, record_guardrail, record_hitl
101
102
  from aid_runtime.types import (
@@ -170,6 +171,12 @@ class _Frame:
170
171
  # the input stage already ran.
171
172
  input_checked: bool = False
172
173
  guardrails: list[GuardrailRecord] = field(default_factory=list)
174
+ # `(name, value)` pairs the declared redact set can strip from the *recorded* copy
175
+ # of every model call this frame makes. Seeded from what the caller supplied and
176
+ # from the tool-call arguments already in the transcript, and grown as the model
177
+ # composes more calls: an agent run has no render, so this is where its bindings
178
+ # come from. The live transcript is never edited -- see `aid_runtime.redaction`.
179
+ redactions: list[Redaction] = field(default_factory=list)
173
180
 
174
181
 
175
182
  @dataclass(slots=True)
@@ -274,8 +281,17 @@ class AgentRuntime:
274
281
  principal: Principal | None = None,
275
282
  memory_key: str | None = None,
276
283
  conversation: Sequence[Message] = (),
284
+ redactions: Sequence[Redaction] = (),
277
285
  ) -> RunResult:
278
- """Run ``agent_id`` to a stop condition on one user message."""
286
+ """Run ``agent_id`` to a stop condition on one user message.
287
+
288
+ ``redactions`` is the caller's ``(name, value)`` bindings for the fields
289
+ ``observability.redact`` withholds. A pipeline binds them when it renders a
290
+ prompt; an agent run has no render, so an application that already holds the
291
+ values -- a typed request, a database row -- supplies them here, and the loop
292
+ adds every value it learns from the tool calls the model composes. They are
293
+ applied to the *recorded* copy only: the model still receives the real text.
294
+ """
279
295
  agent = self._spec.agent(agent_id)
280
296
  self._require_engine(agent)
281
297
  key = memory_key or agent.id
@@ -289,12 +305,13 @@ class AgentRuntime:
289
305
  path=(agent.id,),
290
306
  memory_key=key,
291
307
  )
308
+ frame.redactions[0:0] = list(redactions)
292
309
  start_cost = self._gateway.ledger.cost_usd
293
310
  start_tokens = self._gateway.ledger.total_tokens
294
311
  try:
295
312
  outcome = await self._drive(
296
313
  frame,
297
- principal=principal if principal is not None else Principal(),
314
+ principal=principal if principal is not None else Principal.unauthenticated(),
298
315
  memory_key=key,
299
316
  )
300
317
  except BaseException:
@@ -321,7 +338,7 @@ class AgentRuntime:
321
338
  outcome = await self._resume(
322
339
  checkpoint,
323
340
  resolved,
324
- principal if principal is not None else Principal(),
341
+ principal if principal is not None else Principal.unauthenticated(),
325
342
  )
326
343
  except BaseException:
327
344
  # Same rule as `run`: a resumed run that fails has been billed too.
@@ -367,7 +384,7 @@ class AgentRuntime:
367
384
  frame.messages.append(Message.assistant(answer))
368
385
  await self._remember(agent, answer, checkpoint.memory_key)
369
386
  return self._guardrail_completed(frame, answer)
370
- frame.messages.extend(await self._observe(agent, checkpoint.calls, principal))
387
+ frame.messages.extend(await self._observe(frame, checkpoint.calls, principal))
371
388
  elif escalation is not None:
372
389
  # A person declined to release what the guardrail flagged. That is a
373
390
  # decision, not an error, and the run stops here with the guardrail's
@@ -567,7 +584,7 @@ class AgentRuntime:
567
584
  guardrails=tuple(frame.guardrails),
568
585
  )
569
586
 
570
- frame.messages.extend(await self._observe(agent, guarded, principal))
587
+ frame.messages.extend(await self._observe(frame, guarded, principal))
571
588
 
572
589
  async def _guardrail_text(
573
590
  self,
@@ -837,7 +854,12 @@ class AgentRuntime:
837
854
  )
838
855
 
839
856
  async def _observe(
840
- self, agent: AgentDefinition, calls: Sequence[ToolCall], principal: Principal
857
+ self,
858
+ frame: _Frame,
859
+ calls: Sequence[ToolCall],
860
+ principal: Principal,
861
+ *,
862
+ agent: AgentDefinition | None = None,
841
863
  ) -> list[Message]:
842
864
  """Turn calls into observations, in the order the model asked for them.
843
865
 
@@ -851,10 +873,15 @@ class AgentRuntime:
851
873
  The grant is the agent's declared tool list, and a side-effecting tool
852
874
  additionally needs an ``auth`` policy that holds for this principal. A
853
875
  model cannot repair either: the spec is what is wrong.
876
+
877
+ ``agent`` defaults to the agent the frame is running. The harness engine
878
+ passes it explicitly, because a delegate's tool body executes inside the
879
+ delegate's grant while the run itself continues in the caller's frame.
854
880
  """
881
+ owner = agent if agent is not None else frame.agent
855
882
  known = [call for call in calls if call.name in self._executor.names]
856
883
  for call in known:
857
- self._authorize(agent, call, principal)
884
+ self._authorize(owner, call, principal)
858
885
  executed = {result.call_id: result for result in await self._executor.execute_all(known)}
859
886
  observations: list[Message] = []
860
887
  for call in calls:
@@ -868,7 +895,10 @@ class AgentRuntime:
868
895
  )
869
896
  )
870
897
  continue
871
- observations.append(Message.tool(result.call_id, result.content, name=result.name))
898
+ observations.append(Message.tool(call.id, result.content, name=result.name))
899
+ # Bound after execution: a call this agent may not make raises, and a denied
900
+ # call's arguments are not something the run went on to act on.
901
+ self._bind_calls(frame, calls)
872
902
  return observations
873
903
 
874
904
  def _authorize(self, agent: AgentDefinition, call: ToolCall, principal: Principal) -> None:
@@ -935,7 +965,14 @@ class AgentRuntime:
935
965
  messages = frame.memory.thread.trim(messages)
936
966
  if frame.memory.context:
937
967
  messages = (messages[0], Message.system(frame.memory.context), *messages[1:])
938
- return CompletionRequest(messages=messages, tools=self._tool_definitions(frame.agent))
968
+ return CompletionRequest(
969
+ messages=messages,
970
+ tools=self._tool_definitions(frame.agent),
971
+ # The gateway is the one place that writes model text to a trace, and this
972
+ # is the same pair list a rendered prompt hands it. The provider receives
973
+ # `messages` untouched; only the recorded copy is stripped.
974
+ redactions=tuple(frame.redactions),
975
+ )
939
976
 
940
977
  def _tool_definitions(self, agent: AgentDefinition) -> tuple[ToolDefinition, ...]:
941
978
  definitions = [
@@ -1145,7 +1182,7 @@ class AgentRuntime:
1145
1182
  self._require_engine(agent)
1146
1183
  memory = await self._memory_state(agent, memory_key)
1147
1184
  ledger = self._gateway.ledger
1148
- return _Frame(
1185
+ frame = _Frame(
1149
1186
  agent=agent,
1150
1187
  messages=list(messages),
1151
1188
  alias=agent.model,
@@ -1155,11 +1192,13 @@ class AgentRuntime:
1155
1192
  cost_anchor=ledger.cost_usd,
1156
1193
  token_anchor=ledger.total_tokens,
1157
1194
  )
1195
+ self._bind_message_calls(frame)
1196
+ return frame
1158
1197
 
1159
1198
  async def _frame_from(self, checkpoint: AgentCheckpoint) -> _Frame:
1160
1199
  agent = self._spec.agent(checkpoint.agent_id)
1161
1200
  memory = await self._memory_state(agent, checkpoint.memory_key)
1162
- return _Frame(
1201
+ frame = _Frame(
1163
1202
  agent=agent,
1164
1203
  messages=list(checkpoint.messages),
1165
1204
  alias=checkpoint.alias or agent.model,
@@ -1177,6 +1216,36 @@ class AgentRuntime:
1177
1216
  input_checked=True,
1178
1217
  guardrails=list(checkpoint.guardrails),
1179
1218
  )
1219
+ # The checkpoint carries the transcript, and the transcript carries the calls,
1220
+ # so the resumed frame re-learns its bindings instead of holding state the
1221
+ # checkpoint would have to duplicate -- and duplicate *unredacted*.
1222
+ self._bind_message_calls(frame)
1223
+ return frame
1224
+
1225
+ def _bind_message_calls(self, frame: _Frame) -> None:
1226
+ """Bind the declared names against every tool call the transcript carries."""
1227
+ if not self._spec.redact:
1228
+ return
1229
+ for message in frame.messages:
1230
+ self._bind_calls(frame, message.tool_calls)
1231
+
1232
+ def _bind_calls(self, frame: _Frame, calls: Sequence[ToolCall]) -> None:
1233
+ """Grow the frame's bindings from the arguments the model composed.
1234
+
1235
+ A tool call's arguments are keyed by field name, which is exactly what a redact
1236
+ set names and what prose cannot supply. Pairs already bound are left alone, but a
1237
+ *new* value for an already-bound name is added: two customers' addresses in one
1238
+ run are two values to strip, and keeping only the first would leave the second
1239
+ in every copy recorded after it appeared.
1240
+ """
1241
+ if not self._spec.redact:
1242
+ return
1243
+ known = set(frame.redactions)
1244
+ for call in calls:
1245
+ for pair in bind_redactions(self._spec.redact, call.arguments):
1246
+ if pair not in known:
1247
+ frame.redactions.append(pair)
1248
+ known.add(pair)
1180
1249
 
1181
1250
  async def _memory_state(self, agent: AgentDefinition, memory_key: str) -> _MemoryState:
1182
1251
  thread: ThreadMemory | None = None
@@ -36,14 +36,23 @@ _LOGICAL = frozenset({"and", "or"})
36
36
  class Principal:
37
37
  """Who a policy is evaluated for.
38
38
 
39
- Defaults are the anonymous-but-authenticated caller an app with no auth layer
40
- has: ``isAuthenticated()`` is true and both role and scope sets are empty, so
41
- ``hasRole('admin')`` is false rather than undefined.
39
+ ``authenticated`` defaults to **false** on purpose. A default that is authenticated is
40
+ a silent authorization bug: ``isAuthenticated()`` is the weakest policy the security
41
+ gate accepts on a mutating tool, so a caller the app never identified would satisfy it.
42
+ :meth:`unauthenticated` is the caller an app with no auth layer has -- no roles, no
43
+ scopes, and ``isAuthenticated()`` false, which is the closed answer. Pass
44
+ ``authenticated=True`` only from code that actually verified a token.
42
45
  """
43
46
 
44
47
  roles: frozenset[str] = frozenset()
45
48
  scopes: frozenset[str] = frozenset()
46
- authenticated: bool = True
49
+ authenticated: bool = False
50
+
51
+ @classmethod
52
+ def unauthenticated(cls) -> Principal:
53
+ """The caller a route seeds when nothing verified a token: anonymous, fail-closed."""
54
+
55
+ return cls(authenticated=False)
47
56
 
48
57
 
49
58
  def evaluate_policy(node: Mapping[str, Any], principal: Principal) -> bool:
@@ -24,10 +24,14 @@ missing secret must not degrade into "unsigned".
24
24
 
25
25
  Replay durability is limited by the nonce store, and that limit is real rather than
26
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.
27
+ :class:`SqliteNonceStore` and :class:`PostgresNonceStore` are durable and are what a
28
+ ``state.kind: sqlite`` or ``state.kind: postgres`` declaration gets; only a document that
29
+ declares no store at all falls back to the in-process one, which ``ir/resume-replay-weak``
30
+ states on the document rather than leaving to be discovered.
31
+
32
+ This module stores the *nonce*, not the run. The checkpoint for a paused run still returns
33
+ to the caller, so resuming after a restart is the application's to arrange -- see
34
+ :mod:`aid_runtime.agents.state`.
31
35
  """
32
36
 
33
37
  from __future__ import annotations
@@ -20,6 +20,13 @@ that pauses without supplying one is refused. The one exception is deliberate an
20
20
  ``ApprovalPolicy.APPROVE``/``REJECT`` exist for datasets that are testing something other
21
21
  than the approval, and they are named so a reader of the eval sees the scripted answer.
22
22
 
23
+ **It runs as a stated principal.** An agent's tools and approvals are policies over a
24
+ :class:`Principal`, so an eval that does not name the caller is evaluating an anonymous
25
+ one. That default is the closed answer and is kept deliberately: a mutating tool whose
26
+ policy is ``isAuthenticated()`` is refused for it, and a case written for a signed-in
27
+ caller has to say so. An eval that quietly ran as an authenticated caller would report a
28
+ tool path that production, behind an app which never verified a token, could not take.
29
+
23
30
  What this measures is worth stating plainly, since the module is named after the eval and
24
31
  not the model. When the provider is a recorded transcript or a scripted fake, the model's
25
32
  choices are fixed input: the run verifies that the machinery around the model obeys the
@@ -37,6 +44,7 @@ from enum import StrEnum
37
44
 
38
45
  from aid_runtime.agents.loop import AgentRuntime
39
46
  from aid_runtime.agents.memory import InProcessMemoryStore
47
+ from aid_runtime.agents.policy import Principal
40
48
  from aid_runtime.agents.state import HumanDecision, RunResult, RunStatus
41
49
  from aid_runtime.errors import ConfigurationError, EvalError
42
50
  from aid_runtime.evals.dataset import EvalCase
@@ -88,6 +96,7 @@ class AgentEvalRunner:
88
96
  tools: Iterable[Tool] = (),
89
97
  approval_policy: ApprovalPolicy | str = ApprovalPolicy.FROM_CASE,
90
98
  max_resumes: int = _DEFAULT_MAX_RESUMES,
99
+ principal: Principal | None = None,
91
100
  ) -> None:
92
101
  if not providers:
93
102
  raise ConfigurationError(
@@ -107,6 +116,9 @@ class AgentEvalRunner:
107
116
  self._tools = tuple(tools)
108
117
  self._policy = ApprovalPolicy(approval_policy)
109
118
  self._max_resumes = max_resumes
119
+ #: The caller this eval simulates. Anonymous unless the caller names one, so a
120
+ #: mutating tool is refused rather than silently permitted.
121
+ self._principal = principal if principal is not None else Principal.unauthenticated()
110
122
  #: Cumulative model spend, which is what ``evaluate_once`` differences to charge
111
123
  #: each case. Read from the ledger of the most recent run.
112
124
  self._cost_usd = 0.0
@@ -139,7 +151,7 @@ class AgentEvalRunner:
139
151
  runtime = self._runtime()
140
152
  before = runtime.gateway.ledger.cost_usd
141
153
  try:
142
- result = await runtime.run(self._agent_id, case.input)
154
+ result = await runtime.run(self._agent_id, case.input, principal=self._principal)
143
155
  result, approvals = await self._settle(runtime, case, result)
144
156
  finally:
145
157
  # Charged even when the run raised: a case stopped by a guardrail was billed,
@@ -205,7 +217,7 @@ class AgentEvalRunner:
205
217
  _Rejection(boundary=rejection.boundary, names=rejection.names - names)
206
218
  for rejection in rejections
207
219
  ]
208
- result = await runtime.resume(checkpoint, decision)
220
+ result = await runtime.resume(checkpoint, decision, principal=self._principal)
209
221
  return result, _Approvals(
210
222
  pauses=pauses,
211
223
  decisions=tuple(applied),
aid_runtime/redaction.py CHANGED
@@ -8,13 +8,20 @@ becomes an exact value to remove from the copy that is written to a trace.
8
8
  Redaction applies to the recorded copy only. The model still receives what the
9
9
  application sent, because editing a request would change the answer and a framework
10
10
  that silently rewrote one could not honestly report what it ran.
11
+
12
+ An agent run has no render, so it has no interpolation to learn values from. It binds
13
+ them from the structured records it handles instead -- see :func:`bind_redactions` --
14
+ and the loop hands the result to the gateway, which is the one place that writes model
15
+ text to a trace. Free text the caller sent carries no field name, so a value that
16
+ appears only there is not bound and the limit is stated wherever the guarantee is.
11
17
  """
12
18
 
13
19
  from __future__ import annotations
14
20
 
15
- from collections.abc import Iterable, Sequence
21
+ from collections.abc import Iterable, Mapping, Sequence
22
+ from typing import Any
16
23
 
17
- __all__ = ["REDACTED_FORMAT", "redact_values"]
24
+ __all__ = ["REDACTED_FORMAT", "bind_redactions", "redact_values"]
18
25
 
19
26
  #: What replaces a stripped value. The field name, not the value, so a trace reader
20
27
  #: can still see that a field was present and which one it was.
@@ -34,6 +41,45 @@ def _usable(pairs: Iterable[Redaction]) -> list[Redaction]:
34
41
  return [(name, value) for name, value in pairs if value.strip() != ""]
35
42
 
36
43
 
44
+ def bind_redactions(names: Iterable[str], payload: Any) -> tuple[Redaction, ...]:
45
+ """Bind declared field names to the string values a structured payload carries.
46
+
47
+ This is the agent path's equivalent of a render. A pipeline learns a value from the
48
+ variables it interpolated; an agent loop has no interpolation, so it learns values
49
+ from the structured records it handles -- the arguments of the tool calls the model
50
+ composed, recursing into nested objects and lists. What comes back is the same
51
+ ``(name, value)`` pair the gateway already knows how to strip from a recorded copy.
52
+
53
+ Only strings are bound. A field holding a number or a boolean has no text to match
54
+ in prose, and binding ``"1"`` would rewrite every digit in the transcript instead of
55
+ protecting one field.
56
+
57
+ A name may bind more than one value. Two customers' addresses in one long run are
58
+ two pairs with the same name, and both are stripped: keeping only the first would
59
+ leave the second in every copy recorded after it appeared.
60
+ """
61
+ wanted = frozenset(names)
62
+ if not wanted:
63
+ return ()
64
+ bound: list[Redaction] = []
65
+ _bind_into(wanted, payload, bound)
66
+ return tuple(bound)
67
+
68
+
69
+ def _bind_into(wanted: frozenset[str], payload: Any, bound: list[Redaction]) -> None:
70
+ if isinstance(payload, Mapping):
71
+ for key, value in payload.items():
72
+ if isinstance(key, str) and key in wanted and isinstance(value, str):
73
+ pair = (key, value)
74
+ if value.strip() != "" and pair not in bound:
75
+ bound.append(pair)
76
+ else:
77
+ _bind_into(wanted, value, bound)
78
+ elif isinstance(payload, (list, tuple)):
79
+ for item in payload:
80
+ _bind_into(wanted, item, bound)
81
+
82
+
37
83
  def redact_values(text: str, pairs: Sequence[Redaction]) -> str:
38
84
  """Replace every occurrence of a bound value with ``[redacted:name]``."""
39
85
  if not text or not pairs:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aid-runtime-python
3
- Version: 0.1.163
3
+ Version: 0.1.165
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=aq8poIy2LFueKsPEbAN84Bi3Z2oETd3b_kvauiwj_Jo,15187
1
+ aid_runtime/__init__.py,sha256=ugsNkQFitj5ddM_4-BWbALi_eHkzmd4ansvwgnpK2ac,15227
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
@@ -11,7 +11,7 @@ aid_runtime/metrics.py,sha256=w55qPlFRQXUfASxpskgYiSeFcFxkL_mwbDp2IhevAbg,6050
11
11
  aid_runtime/pipeline.py,sha256=Y2jiiYISLLxgBKGBj5J2rseEDzE8RXP8v5pJ_edjHfM,6334
12
12
  aid_runtime/prompts.py,sha256=kA2sBIy-e7R0OG6GO4-Knf30zHL4OA6Gt4uPZyNon9o,7646
13
13
  aid_runtime/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- aid_runtime/redaction.py,sha256=25oFaFjzmEP9asWVwyWO8bg42mGLncLnvuHQeR5qKnQ,1993
14
+ aid_runtime/redaction.py,sha256=EaWtykRHAfnhJdvV_nAVhvYOfRZGqUxTcOugkjiIRWM,4253
15
15
  aid_runtime/steps.py,sha256=44v8-ebN77VGZePmfhBYi0KORFBrH2GWFSzlfczaJhs,12047
16
16
  aid_runtime/structured.py,sha256=Uga-VoGJN56lUtr-M3nmUjAKGF32cAAk-p7WceUgPzg,5061
17
17
  aid_runtime/telemetry.py,sha256=ykAXCL3XFi0yok3xr-fjD3oGvVycdfyrqJ8nGKC_ZHc,12872
@@ -19,19 +19,19 @@ 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
21
  aid_runtime/agents/__init__.py,sha256=rf3k0hxHDO60S1TrON6d2-rTv1N8V4WvF47xsJ5bhE0,3709
22
- aid_runtime/agents/chat_model.py,sha256=fZdCmSpoECuBVGZE1s8NmT2erT33RhDuLh3yJM6kAJE,14808
23
- aid_runtime/agents/deep_agents.py,sha256=Eg_BLm2cg7T_tXSxR7ag8SEvTMCFBLHoIvln3BoWORw,26966
22
+ aid_runtime/agents/chat_model.py,sha256=RHMA3_Yb8UE14YQo8k-ylUZiQnOvUKDnl1AEKBG_rgU,16526
23
+ aid_runtime/agents/deep_agents.py,sha256=ArNm1MGDgsrO5AKkin0WYzDhGcMM7Q0XO0wi8qFUT5o,27338
24
24
  aid_runtime/agents/engine.py,sha256=3cXCYY806URDblYD500cfw7873IoVCy8BH1d4h2YAsc,5789
25
25
  aid_runtime/agents/guardrails.py,sha256=0HhbToZBxPZHEDRLyD9BGS_jmV-TkKPGEhRynYxLXx8,32813
26
- aid_runtime/agents/ir.py,sha256=MgqX5gEkq7vimXojtSNb5MuVeTIZaWkZCFitxAqSAe0,32855
27
- aid_runtime/agents/loop.py,sha256=gTfFRcRuGuyZpNdw2PK168A9Cp6LHBLJMUpHUxXPTnE,55952
26
+ aid_runtime/agents/ir.py,sha256=kBCvMYrLAS6umkl_JK-JwJhOxvDRXLV0wiZ_r6CgvII,34088
27
+ aid_runtime/agents/loop.py,sha256=fKT5iemOqoOuSXw_zbu-BxJzDdWqyBZqcZZFcfG1h_g,59587
28
28
  aid_runtime/agents/managed.py,sha256=SFyx6Rca2aoiMzA9q6B4Nfes6ZCjn_5_zN0SxzemIII,23247
29
29
  aid_runtime/agents/memory.py,sha256=6_D6k2bzAiR2euNvzr6HB28wsUUq-R-WTQc12gkB8ao,9156
30
- aid_runtime/agents/policy.py,sha256=ael0EW_hWfLu95rbqFMrR4WyqAPtgiSNvNw97xnthdw,6122
31
- aid_runtime/agents/resume.py,sha256=VAjJja2ZvXLLSRgz9Z_2b5Cs9Af5Kevr5qjuDpslpuw,17035
30
+ aid_runtime/agents/policy.py,sha256=IbJ9LQDPOumwup5K_eeyFAfCLFuMqEK6iSvBrM6o16Q,6610
31
+ aid_runtime/agents/resume.py,sha256=FM2SbsQZEOCKtHkEsu8riIcbsXYf9ieaioZ32UBN-to,17306
32
32
  aid_runtime/agents/state.py,sha256=feXZtQeD3vcKpNUPsCXby0J15UqkoD4_Gi-aT3Up8RI,7174
33
33
  aid_runtime/evals/__init__.py,sha256=5_qUGwiKR2l4p-F8RZ9QnxzFOxtNj7DWoEsA8uNyHIs,1991
34
- aid_runtime/evals/agent_runner.py,sha256=E1Vg48gNAeQzGGSyp0cK8H5mxGlVEPBq-FTaaTQ-CLE,12594
34
+ aid_runtime/evals/agent_runner.py,sha256=sffFGqZDBLmKkce6t82IaWJLHNq-q7HuSmIM61uEkoU,13513
35
35
  aid_runtime/evals/dataset.py,sha256=ZmTP-jWx9f2udYPyzvTtOuUse5Mp-uj5WNBPy-7aHKM,5946
36
36
  aid_runtime/evals/gate.py,sha256=uYUOw57MaGqSOsMvbB0C6MrjW4IbUJ57izyD6FSxkxw,17676
37
37
  aid_runtime/evals/metrics.py,sha256=LvzKgW-7CNxcB0MmDXakDnwdgyzjpH8ceHq7mdi8mw4,28541
@@ -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.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,,
66
+ aid_runtime_python-0.1.165.dist-info/METADATA,sha256=Vtv64gwZNI-QZ1m9b4MgWRblZQPHjkTT86WhXiI8hUI,17163
67
+ aid_runtime_python-0.1.165.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
68
+ aid_runtime_python-0.1.165.dist-info/top_level.txt,sha256=QvODgNVRDDMmLcTnoIQ4jYnhqf-N4b9sHWEmaUUxp44,12
69
+ aid_runtime_python-0.1.165.dist-info/RECORD,,