agenticsafetyeval 0.2.0__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.
Files changed (54) hide show
  1. agenticsafetyeval/__init__.py +3 -0
  2. agenticsafetyeval/__main__.py +6 -0
  3. agenticsafetyeval/agents/__init__.py +1 -0
  4. agenticsafetyeval/agents/llm_session.py +157 -0
  5. agenticsafetyeval/agents/session.py +127 -0
  6. agenticsafetyeval/backends/__init__.py +1 -0
  7. agenticsafetyeval/backends/state_provider.py +87 -0
  8. agenticsafetyeval/claims/__init__.py +1 -0
  9. agenticsafetyeval/claims/llm_extractor.py +131 -0
  10. agenticsafetyeval/claims/verifier.py +398 -0
  11. agenticsafetyeval/cli/__init__.py +5 -0
  12. agenticsafetyeval/cli/app.py +63 -0
  13. agenticsafetyeval/cli/certify_cmd.py +50 -0
  14. agenticsafetyeval/cli/common.py +121 -0
  15. agenticsafetyeval/cli/judge_cmd.py +167 -0
  16. agenticsafetyeval/cli/matrix_cmd.py +117 -0
  17. agenticsafetyeval/cli/regrade_cmd.py +70 -0
  18. agenticsafetyeval/cli/report_cmd.py +59 -0
  19. agenticsafetyeval/cli/run_cmd.py +328 -0
  20. agenticsafetyeval/cli/scaffold.py +90 -0
  21. agenticsafetyeval/cli/scenario_cmd.py +57 -0
  22. agenticsafetyeval/conformance.py +177 -0
  23. agenticsafetyeval/core/__init__.py +1 -0
  24. agenticsafetyeval/core/models.py +130 -0
  25. agenticsafetyeval/harness/__init__.py +1 -0
  26. agenticsafetyeval/harness/session_runner.py +299 -0
  27. agenticsafetyeval/judges/__init__.py +25 -0
  28. agenticsafetyeval/judges/llm_judge.py +114 -0
  29. agenticsafetyeval/judges/transcript.py +66 -0
  30. agenticsafetyeval/llm/__init__.py +33 -0
  31. agenticsafetyeval/llm/client.py +421 -0
  32. agenticsafetyeval/llm/parsing.py +31 -0
  33. agenticsafetyeval/llm/prompts.py +51 -0
  34. agenticsafetyeval/mocks/__init__.py +1 -0
  35. agenticsafetyeval/mocks/banking_session.py +264 -0
  36. agenticsafetyeval/py.typed +1 -0
  37. agenticsafetyeval/reporting/__init__.py +29 -0
  38. agenticsafetyeval/reporting/html.py +44 -0
  39. agenticsafetyeval/reporting/report.py +95 -0
  40. agenticsafetyeval/reporting/sink.py +117 -0
  41. agenticsafetyeval/reporting/site.py +42 -0
  42. agenticsafetyeval/scenarios/__init__.py +1 -0
  43. agenticsafetyeval/scenarios/loader.py +79 -0
  44. agenticsafetyeval/scoring/__init__.py +1 -0
  45. agenticsafetyeval/scoring/invariants.py +124 -0
  46. agenticsafetyeval/scoring/state.py +23 -0
  47. agenticsafetyeval/trace/__init__.py +1 -0
  48. agenticsafetyeval/trace/recorder.py +127 -0
  49. agenticsafetyeval-0.2.0.dist-info/METADATA +519 -0
  50. agenticsafetyeval-0.2.0.dist-info/RECORD +54 -0
  51. agenticsafetyeval-0.2.0.dist-info/WHEEL +4 -0
  52. agenticsafetyeval-0.2.0.dist-info/entry_points.txt +2 -0
  53. agenticsafetyeval-0.2.0.dist-info/licenses/LICENSE +201 -0
  54. agenticsafetyeval-0.2.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,328 @@
1
+ """The ``run`` command: evaluate a session agent on black-box scenarios."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import uuid
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+ from typing import Annotated, cast
12
+
13
+ import typer
14
+
15
+ from agenticsafetyeval.agents.session import SessionAgent
16
+ from agenticsafetyeval.backends.state_provider import StateProvider
17
+ from agenticsafetyeval.claims.llm_extractor import LLMClaimExtractor
18
+ from agenticsafetyeval.cli.common import (
19
+ MODEL_SPEC_HELP,
20
+ import_object,
21
+ parse_model_options,
22
+ parse_model_spec,
23
+ )
24
+ from agenticsafetyeval.core.models import Domain, Scenario
25
+ from agenticsafetyeval.harness.session_runner import run_session_scenario
26
+ from agenticsafetyeval.llm.client import ModelSpec, build_client
27
+ from agenticsafetyeval.llm.prompts import CLAIM_EXTRACTOR_PROMPT
28
+ from agenticsafetyeval.mocks.banking_session import reference_session_pair, unsafe_session_pair
29
+ from agenticsafetyeval.reporting import RecordSink, SavedRunRecord, build_leaderboard, build_sink
30
+ from agenticsafetyeval.scenarios.loader import discover_scenarios, load_scenario
31
+
32
+ SessionPair = tuple[SessionAgent, StateProvider]
33
+
34
+
35
+ def _canonical_hash(payload: object) -> str:
36
+ """SHA-256 of canonical JSON, for scenario/snapshot provenance hashes."""
37
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
38
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
39
+
40
+
41
+ def _session_pair_factory(
42
+ spec: str, state_provider_spec: str | None
43
+ ) -> Callable[[Scenario], SessionPair]:
44
+ """Build (session agent, state provider) pairs for black-box scenarios."""
45
+ if spec == "session-reference":
46
+ return reference_session_pair
47
+ if spec == "session-unsafe":
48
+ return unsafe_session_pair
49
+ agent_class = import_object(spec)
50
+ if not callable(agent_class) or not callable(getattr(agent_class, "say", None)):
51
+ raise typer.BadParameter(f"{spec} does not implement SessionAgent.say")
52
+ if state_provider_spec is None:
53
+ raise typer.BadParameter(
54
+ "black-box runs with a custom session agent require "
55
+ "--state-provider 'package.module:ClassName'"
56
+ )
57
+ provider_class = import_object(state_provider_spec)
58
+ if not callable(provider_class):
59
+ raise typer.BadParameter(f"{state_provider_spec} is not callable")
60
+
61
+ def build(_scenario: Scenario) -> SessionPair:
62
+ return cast(SessionAgent, agent_class()), cast(StateProvider, provider_class())
63
+
64
+ return build
65
+
66
+
67
+ def _select_scenarios(
68
+ suite: Path, domain: Domain, requested: list[str], category: list[str]
69
+ ) -> tuple[Scenario, ...]:
70
+ scenarios = discover_scenarios(suite, domain=domain)
71
+ if requested:
72
+ selected: dict[str, Scenario] = {}
73
+ unknown: list[str] = []
74
+ by_id = {item.scenario_id: item for item in scenarios}
75
+ for name in requested:
76
+ candidate = Path(name)
77
+ if candidate.is_file() and candidate.suffix in (".yaml", ".yml"):
78
+ item = load_scenario(candidate, suite)
79
+ selected[item.scenario_id] = item
80
+ elif name in by_id:
81
+ selected[name] = by_id[name]
82
+ else:
83
+ unknown.append(name)
84
+ if unknown:
85
+ raise typer.BadParameter(f"unknown scenario(s): {', '.join(unknown)}")
86
+ scenarios = tuple(selected.values())
87
+ if category:
88
+ scenarios = tuple(item for item in scenarios if item.category.value in category)
89
+ return scenarios
90
+
91
+
92
+ async def _run_all(
93
+ scenarios: tuple[Scenario, ...],
94
+ repeats: int,
95
+ build_pair: Callable[[Scenario], SessionPair],
96
+ agent_label: str,
97
+ sink: RecordSink,
98
+ extractor_spec: ModelSpec | None = None,
99
+ *,
100
+ concurrency: int = 1,
101
+ retries: int = 0,
102
+ retry_backoff: float = 1.0,
103
+ provider_trust: str = "self_reported",
104
+ provider_probe: bool = False,
105
+ ) -> list[SavedRunRecord]:
106
+ """Run every scenario/repeat; write one record each to ``sink``.
107
+
108
+ Runs are independent: up to ``concurrency`` execute at once, each with
109
+ its own fresh agent/provider pair and its own ``run_id``. A run that
110
+ aborts (agent, extractor, or provider raised) is retried with a fresh
111
+ pair up to ``retries`` times with exponential backoff; a completed run
112
+ that merely fails grading is never retried. Records are returned in
113
+ scenario/repeat order regardless of completion order.
114
+ """
115
+ extractor_client = build_client(extractor_spec) if extractor_spec is not None else None
116
+ semaphore = asyncio.Semaphore(max(1, concurrency))
117
+
118
+ async def one(item: Scenario, repeat: int) -> SavedRunRecord:
119
+ async with semaphore:
120
+ attempts = 0
121
+ while True:
122
+ attempts += 1
123
+ run_id = uuid.uuid4().hex
124
+ extractor = (
125
+ LLMClaimExtractor(
126
+ extractor_client,
127
+ CLAIM_EXTRACTOR_PROMPT,
128
+ json.dumps(item.initial_state, sort_keys=True),
129
+ )
130
+ if extractor_client is not None
131
+ else None
132
+ )
133
+ session_agent, provider = build_pair(item)
134
+ result = await run_session_scenario(
135
+ item,
136
+ session_agent,
137
+ provider,
138
+ claim_extractor=extractor,
139
+ run_id=run_id,
140
+ provider_probe=provider_probe,
141
+ )
142
+ if result.completed or attempts > retries:
143
+ break
144
+ await asyncio.sleep(retry_backoff * (2 ** (attempts - 1)))
145
+ record = SavedRunRecord(
146
+ scenario_id=result.scenario_id,
147
+ repeat=repeat,
148
+ run_id=run_id,
149
+ attempts=attempts,
150
+ agent=agent_label,
151
+ passed=result.passed,
152
+ completed=result.completed,
153
+ aborted_reason=result.aborted_reason,
154
+ final_state=result.final_state,
155
+ state_score=result.state_score,
156
+ events=result.events,
157
+ claims=result.claims,
158
+ claim_verdicts=result.claim_verdicts,
159
+ reply_violations=result.reply_violations,
160
+ invariant_violations=result.invariant_violations,
161
+ provider_trust=provider_trust, # type: ignore[arg-type]
162
+ snapshot_hash=_canonical_hash(result.final_state),
163
+ scenario_sha256=_canonical_hash(item.model_dump(mode="json")),
164
+ )
165
+ sink.write(record)
166
+ return record
167
+
168
+ try:
169
+ tasks = [
170
+ asyncio.create_task(one(item, repeat))
171
+ for item in scenarios
172
+ for repeat in range(repeats)
173
+ ]
174
+ return list(await asyncio.gather(*tasks))
175
+ finally:
176
+ sink.close()
177
+
178
+
179
+ def register(app: typer.Typer) -> None:
180
+ """Register the ``run`` command on ``app``."""
181
+
182
+ @app.command()
183
+ def run(
184
+ agent: Annotated[
185
+ str,
186
+ typer.Option(
187
+ help="'session-reference'/'session-unsafe' (black-box demo), "
188
+ "or a SessionAgent 'package.module:ClassName'"
189
+ ),
190
+ ] = "session-reference",
191
+ suite: Annotated[Path, typer.Option(help="Benchmark root directory")] = Path(
192
+ "safeorderbench"
193
+ ),
194
+ scenario: Annotated[
195
+ list[str], typer.Option(help="Scenario id or YAML path (repeatable)")
196
+ ] = [], # noqa: B006
197
+ category: Annotated[list[str], typer.Option(help="Limit to a category (repeatable)")] = [], # noqa: B006
198
+ domain: Annotated[str, typer.Option(help="Scenario domain, e.g. banking")] = "banking",
199
+ repeats: Annotated[int, typer.Option(help="Runs per scenario; rates aggregate")] = 1,
200
+ state_provider: Annotated[
201
+ str | None,
202
+ typer.Option(help="StateProvider 'package.module:ClassName' for custom agents"),
203
+ ] = None,
204
+ extractor_model: Annotated[
205
+ str | None,
206
+ typer.Option(
207
+ help=f"Extract reply claims with this {MODEL_SPEC_HELP} "
208
+ "(key from the provider's env var; never on the command line)"
209
+ ),
210
+ ] = None,
211
+ extractor_api_key_env: Annotated[
212
+ str | None,
213
+ typer.Option(help="Env var holding the extractor key (default: provider's var)"),
214
+ ] = None,
215
+ extractor_base_url: Annotated[
216
+ str | None,
217
+ typer.Option(help="Endpoint URL for the extractor model (compatible/Azure/local)"),
218
+ ] = None,
219
+ extractor_api_version: Annotated[
220
+ str | None,
221
+ typer.Option(help="API version for the extractor endpoint (e.g. Azure OpenAI)"),
222
+ ] = None,
223
+ extractor_model_option: Annotated[
224
+ list[str],
225
+ typer.Option(
226
+ help="Provider option for the extractor as 'key=value' (repeatable, "
227
+ "e.g. aws_region_name=us-east-1 for bedrock)"
228
+ ),
229
+ ] = [], # noqa: B006
230
+ min_pass_rate: Annotated[
231
+ float,
232
+ typer.Option(
233
+ help="Exit 0 only if the aggregate pass rate reaches this "
234
+ "threshold (pre-deployment CI gate)"
235
+ ),
236
+ ] = 1.0,
237
+ concurrency: Annotated[
238
+ int,
239
+ typer.Option(
240
+ help="Max runs in flight at once (each run needs its own "
241
+ "isolated agent/provider pair and sandbox partition)"
242
+ ),
243
+ ] = 1,
244
+ retries: Annotated[
245
+ int,
246
+ typer.Option(help="Retries for aborted runs (fresh pair each attempt)"),
247
+ ] = 0,
248
+ retry_backoff: Annotated[
249
+ float, typer.Option(help="Base seconds for exponential retry backoff")
250
+ ] = 1.0,
251
+ provider_trust: Annotated[
252
+ str,
253
+ typer.Option(
254
+ help="Who operated the StateProvider: harness | auditor | "
255
+ "self_reported (docs/trust_model.md)"
256
+ ),
257
+ ] = "self_reported",
258
+ provider_probe: Annotated[
259
+ bool,
260
+ typer.Option(help="Require a randomized provider probe round-trip before each run"),
261
+ ] = False,
262
+ sink: Annotated[
263
+ str, typer.Option(help="Record sink: file (one JSON per run) | sqlite (one DB)")
264
+ ] = "file",
265
+ out: Annotated[Path, typer.Option(help="Directory (file sink) or DB path (sqlite)")] = Path(
266
+ "artifacts/cli_runs"
267
+ ),
268
+ ) -> None:
269
+ """Run a session agent on black-box scenarios; one JSON record per run.
270
+
271
+ The agent is driven by scripted customer utterances and executes
272
+ its own tools internally; the harness seeds and reads its world
273
+ through a StateProvider and grades the final state.
274
+ """
275
+ try:
276
+ domain_value = Domain(domain)
277
+ except ValueError:
278
+ raise typer.BadParameter(f"unknown domain {domain!r}") from None
279
+ if repeats < 1:
280
+ raise typer.BadParameter("repeats must be at least 1")
281
+ if concurrency < 1:
282
+ raise typer.BadParameter("concurrency must be at least 1")
283
+ if retries < 0 or retry_backoff < 0:
284
+ raise typer.BadParameter("retries and retry-backoff must be non-negative")
285
+ if not 0.0 < min_pass_rate <= 1.0:
286
+ raise typer.BadParameter("min-pass-rate must be in (0, 1]")
287
+ if provider_trust not in {"harness", "auditor", "self_reported"}:
288
+ raise typer.BadParameter("provider-trust must be harness | auditor | self_reported")
289
+ extractor_spec = (
290
+ parse_model_spec(
291
+ extractor_model,
292
+ extractor_api_key_env,
293
+ extractor_base_url,
294
+ extractor_api_version,
295
+ parse_model_options(extractor_model_option),
296
+ )
297
+ if extractor_model
298
+ else None
299
+ )
300
+ scenarios = _select_scenarios(suite, domain_value, scenario, category)
301
+ if not scenarios:
302
+ typer.echo("no scenarios matched", err=True)
303
+ raise typer.Exit(code=2)
304
+ build_pair = _session_pair_factory(agent, state_provider)
305
+
306
+ try:
307
+ record_sink = build_sink(sink, out)
308
+ except ValueError as error:
309
+ raise typer.BadParameter(str(error)) from None
310
+ records = asyncio.run(
311
+ _run_all(
312
+ scenarios,
313
+ repeats,
314
+ build_pair,
315
+ agent,
316
+ record_sink,
317
+ extractor_spec,
318
+ concurrency=concurrency,
319
+ retries=retries,
320
+ retry_backoff=retry_backoff,
321
+ provider_trust=provider_trust,
322
+ provider_probe=provider_probe,
323
+ )
324
+ )
325
+ board = build_leaderboard(records)
326
+ typer.echo(json.dumps(board, indent=2, sort_keys=True))
327
+ pass_rate = sum(1 for record in records if record.passed) / len(records)
328
+ raise typer.Exit(code=0 if pass_rate >= min_pass_rate else 1)
@@ -0,0 +1,90 @@
1
+ """The ``new-session-agent`` scaffolding command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import typer
10
+
11
+ _NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")
12
+
13
+
14
+ def register(app: typer.Typer) -> None:
15
+ """Register the scaffolding command on ``app``."""
16
+
17
+ @app.command("new-session-agent")
18
+ def new_session_agent(
19
+ name: str, out: Annotated[Path, typer.Option(help="Parent directory")] = Path(".")
20
+ ) -> None:
21
+ """Scaffold a starter project: session agent + state provider."""
22
+ if not _NAME.match(name):
23
+ raise typer.BadParameter(
24
+ f"name must start with a letter and contain only letters, digits, '-'/'_', "
25
+ f"got {name!r}"
26
+ )
27
+ root = out / name
28
+ if root.exists():
29
+ raise typer.BadParameter(f"{root} already exists; refusing to overwrite")
30
+ package = root / name.replace("-", "_")
31
+ package.mkdir(parents=True)
32
+ (package / "__init__.py").write_text(
33
+ '"""Session-agent starter package."""\n', encoding="utf-8"
34
+ )
35
+ (package / "agent.py").write_text(_STARTER_SESSION_AGENT, encoding="utf-8")
36
+ (root / "README.md").write_text(
37
+ f"# {name}\n\nStarter project (see docs/agent_contract.md). Certify it with:\n\n"
38
+ f"```bash\nagenticsafetyeval certify-agent \\\n"
39
+ f" --agent {package.name}.agent:StarterSessionAgent\n"
40
+ f"agenticsafetyeval certify-state-provider "
41
+ f"--provider {package.name}.agent:StarterStateProvider\n"
42
+ "```\n",
43
+ encoding="utf-8",
44
+ )
45
+ typer.echo(str(root))
46
+
47
+
48
+ _STARTER_SESSION_AGENT = '''"""Starter: a session agent plus its state provider.
49
+
50
+ Replace the echo logic with calls into your agent, and the in-memory
51
+ provider with seed/snapshot/reset against your sandbox. See
52
+ docs/agent_contract.md.
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import copy
58
+
59
+ from agenticsafetyeval.agents.session import SessionReply
60
+ from agenticsafetyeval.core.models import JsonObject
61
+
62
+
63
+ class StarterSessionAgent:
64
+ """Utterance in, reply out; executes its own tools internally."""
65
+
66
+ def __init__(self) -> None:
67
+ self._turns = 0
68
+
69
+ async def say(self, customer_text: str) -> SessionReply:
70
+ self._turns += 1
71
+ # TODO: forward customer_text to your agent and return its reply.
72
+ # Report structured outcomes as metadata (checked, never trusted).
73
+ return SessionReply(text=f"You said: {customer_text}", metadata={"turns": self._turns})
74
+
75
+
76
+ class StarterStateProvider:
77
+ """Seed, read, and reset your sandbox state for one scenario."""
78
+
79
+ def __init__(self) -> None:
80
+ self._state: JsonObject = {}
81
+
82
+ def seed(self, initial_state: JsonObject) -> None:
83
+ self._state = copy.deepcopy(initial_state)
84
+
85
+ def snapshot(self) -> JsonObject:
86
+ return copy.deepcopy(self._state)
87
+
88
+ def reset(self) -> None:
89
+ self._state = {}
90
+ '''
@@ -0,0 +1,57 @@
1
+ """The ``explain-scenario`` and ``lint-scenario`` commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Annotated
8
+
9
+ import typer
10
+
11
+ from agenticsafetyeval.scenarios.loader import load_scenario
12
+
13
+
14
+ def register(app: typer.Typer) -> None:
15
+ """Register the scenario inspection commands on ``app``."""
16
+
17
+ @app.command("explain-scenario")
18
+ def explain_scenario(
19
+ scenario_path: Path,
20
+ benchmark_root: Annotated[Path, typer.Option(help="Benchmark root directory")] = Path(
21
+ "safeorderbench"
22
+ ),
23
+ ) -> None:
24
+ """Print a plain-English summary of a scenario."""
25
+ item = load_scenario(scenario_path, benchmark_root)
26
+ typer.echo(
27
+ f"Scenario: {item.scenario_id} "
28
+ f"({item.domain.value}, {item.category.value}, {item.kind.value})"
29
+ )
30
+ typer.echo(f"What it is about: {item.description}")
31
+ typer.echo(f"Starting state: {json.dumps(item.initial_state, sort_keys=True)}")
32
+ for turn in item.customer_turns:
33
+ typer.echo(f"Customer says ({turn.turn_id}): {turn.message}")
34
+ for clarification in item.clarifications:
35
+ typer.echo(f"If asked about '{clarification.match}': {clarification.answer}")
36
+ typer.echo(f"Acceptable endings: {len(item.authorized_final_states)}")
37
+ for state in item.authorized_final_states:
38
+ typer.echo(f" ending: {json.dumps(state, sort_keys=True)}")
39
+
40
+ @app.command("lint-scenario")
41
+ def lint_scenario(
42
+ scenario_path: Path,
43
+ benchmark_root: Annotated[Path, typer.Option(help="Benchmark root directory")] = Path(
44
+ "safeorderbench"
45
+ ),
46
+ ) -> None:
47
+ """Check a scenario loads and passes model validation.
48
+
49
+ All consistency rules live in the ``Scenario`` model; a scenario
50
+ that loads is valid, so lint adds no rules of its own.
51
+ """
52
+ try:
53
+ item = load_scenario(scenario_path, benchmark_root)
54
+ except Exception as error: # noqa: BLE001 - lint reports load failures
55
+ typer.echo(f"INVALID: {type(error).__name__}: {error}")
56
+ raise typer.Exit(code=1) from None
57
+ typer.echo(f"OK: {item.scenario_id}")
@@ -0,0 +1,177 @@
1
+ """Conformance checks for black-box (Profile C) integrations.
2
+
3
+ For a self-executing agent, its session adapter and its state provider
4
+ are the trust surface. These checks certify that surface: the adapter
5
+ answers in contract shape and keeps runs isolated; the provider seeds,
6
+ reads, and resets the agent owner's world faithfully.
7
+
8
+ Every check builds a fresh subject from the factory, so checks are
9
+ independent and order does not matter. A factory that raises fails every
10
+ check instead of crashing certification.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import uuid
17
+ from collections.abc import Callable, Coroutine
18
+
19
+ from agenticsafetyeval.agents.session import SessionAgent, SessionReply
20
+ from agenticsafetyeval.backends.state_provider import StateProvider
21
+ from agenticsafetyeval.core.models import FrozenModel, JsonObject
22
+
23
+
24
+ class ConformanceCheck(FrozenModel):
25
+ """One contract check outcome."""
26
+
27
+ check_id: str
28
+ name: str
29
+ passed: bool
30
+ note: str = ""
31
+
32
+
33
+ class ConformanceReport(FrozenModel):
34
+ """Machine-readable conformance result for one subject."""
35
+
36
+ checks: tuple[ConformanceCheck, ...]
37
+ subject: str = "session-agent"
38
+
39
+ @property
40
+ def passed(self) -> bool:
41
+ """Whether every check passed."""
42
+ return all(check.passed for check in self.checks)
43
+
44
+ @property
45
+ def passed_count(self) -> int:
46
+ return sum(1 for check in self.checks if check.passed)
47
+
48
+ @property
49
+ def total_count(self) -> int:
50
+ return len(self.checks)
51
+
52
+
53
+ SessionAgentFactory = Callable[[], SessionAgent]
54
+ StateProviderFactory = Callable[[], StateProvider]
55
+
56
+
57
+ async def check_session_agent(factory: SessionAgentFactory) -> ConformanceReport:
58
+ """Run the session-agent adapter checks, each on a fresh agent."""
59
+ checks: list[ConformanceCheck] = []
60
+
61
+ async def record(
62
+ check_id: str, name: str, fn: Callable[[], Coroutine[object, object, tuple[bool, str]]]
63
+ ) -> None:
64
+ try:
65
+ passed, note = await fn()
66
+ except Exception as error: # noqa: BLE001 - a crashing adapter fails
67
+ checks.append(
68
+ ConformanceCheck(
69
+ check_id=check_id,
70
+ name=name,
71
+ passed=False,
72
+ note=f"raised {type(error).__name__}: {error}",
73
+ )
74
+ )
75
+ return
76
+ checks.append(ConformanceCheck(check_id=check_id, name=name, passed=passed, note=note))
77
+
78
+ async def agt01() -> tuple[bool, str]:
79
+ reply = await factory().say("Hello, what can you do?")
80
+ ok = isinstance(reply, SessionReply) and isinstance(reply.text, str)
81
+ return ok, f"reply type={type(reply).__name__}"
82
+
83
+ await record("AGT-01", "responds to an utterance with a session reply", agt01)
84
+
85
+ async def agt02() -> tuple[bool, str]:
86
+ reply = await factory().say("")
87
+ return isinstance(reply.text, str), "empty utterance tolerated"
88
+
89
+ await record("AGT-02", "tolerates an empty utterance", agt02)
90
+
91
+ async def agt03() -> tuple[bool, str]:
92
+ reply = await factory().say("Tell me something.")
93
+ json.dumps(reply.metadata) # must be JSON-serializable
94
+ return isinstance(reply.metadata, dict), "metadata is a JSON object"
95
+
96
+ await record("AGT-03", "reply metadata is JSON-serializable", agt03)
97
+
98
+ async def agt04() -> tuple[bool, str]:
99
+ token = f"probe-{uuid.uuid4().hex}"
100
+ first, second = factory(), factory()
101
+ if first is second:
102
+ return False, "factory returned the same instance twice"
103
+ await first.say(f"Remember this code: {token}")
104
+ reply = await second.say("What code did I ask you to remember?")
105
+ return token not in reply.text, "no state leaks between fresh instances"
106
+
107
+ await record("AGT-04", "fresh instances are session-isolated", agt04)
108
+
109
+ async def agt05() -> tuple[bool, str]:
110
+ probe = factory()
111
+ for _ in range(5):
112
+ reply = await probe.say("Continue.")
113
+ if not isinstance(reply, SessionReply) or not isinstance(reply.text, str):
114
+ return False, f"utterance returned {type(reply).__name__}"
115
+ return True, "five consecutive utterances answered with session replies"
116
+
117
+ await record("AGT-05", "sustains a multi-turn conversation", agt05)
118
+
119
+ return ConformanceReport(checks=tuple(checks), subject="session-agent")
120
+
121
+
122
+ def check_state_provider(factory: StateProviderFactory) -> ConformanceReport:
123
+ """Run the state-provider checks, each on a fresh provider."""
124
+ checks: list[ConformanceCheck] = []
125
+
126
+ def record(check_id: str, name: str, fn: Callable[[], tuple[bool, str]]) -> None:
127
+ try:
128
+ passed, note = fn()
129
+ except Exception as error: # noqa: BLE001 - a crashing provider fails
130
+ checks.append(
131
+ ConformanceCheck(
132
+ check_id=check_id,
133
+ name=name,
134
+ passed=False,
135
+ note=f"raised {type(error).__name__}: {error}",
136
+ )
137
+ )
138
+ return
139
+ checks.append(ConformanceCheck(check_id=check_id, name=name, passed=passed, note=note))
140
+
141
+ probe_state: JsonObject = {"__provider_probe__": {"items": [1, 2, 3], "flag": True}}
142
+
143
+ def sp01() -> tuple[bool, str]:
144
+ provider = factory()
145
+ provider.seed(probe_state)
146
+ return provider.snapshot() == probe_state, "seed then snapshot round-trips"
147
+
148
+ record("SP-01", "seed/snapshot round-trip", sp01)
149
+
150
+ def sp02() -> tuple[bool, str]:
151
+ provider = factory()
152
+ provider.seed(probe_state)
153
+ snap = provider.snapshot()
154
+ snap["__provider_probe__"] = "mutated"
155
+ return provider.snapshot() == probe_state, "snapshot isolation"
156
+
157
+ record("SP-02", "snapshot isolation", sp02)
158
+
159
+ def sp03() -> tuple[bool, str]:
160
+ provider = factory()
161
+ provider.seed(probe_state)
162
+ provider.reset()
163
+ return "__provider_probe__" not in provider.snapshot(), "reset removes seeded state"
164
+
165
+ record("SP-03", "reset clears run residue", sp03)
166
+
167
+ def sp04() -> tuple[bool, str]:
168
+ provider = factory()
169
+ provider.seed(probe_state)
170
+ first = provider.snapshot()
171
+ provider.reset()
172
+ provider.seed(probe_state)
173
+ return provider.snapshot() == first, "re-seed after reset is deterministic"
174
+
175
+ record("SP-04", "deterministic re-seed", sp04)
176
+
177
+ return ConformanceReport(checks=tuple(checks), subject="state-provider")
@@ -0,0 +1 @@
1
+ """Shared, provider-neutral schemas and interfaces."""