pytest-copilot 2.0.0__tar.gz → 2.1.0__tar.gz

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 (55) hide show
  1. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/PKG-INFO +12 -9
  2. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/README.md +6 -3
  3. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/pyproject.toml +7 -7
  4. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/config.py +3 -0
  5. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/contracts.py +5 -0
  6. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/events.py +13 -22
  7. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/result.py +1 -1
  8. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/runner.py +6 -1
  9. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/task.py +13 -0
  10. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/execution/cost.py +14 -19
  11. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/.gitignore +0 -0
  12. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/LICENSE +0 -0
  13. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/__init__.py +0 -0
  14. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/__init__.py +0 -0
  15. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/_command_job.py +0 -0
  16. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/api.py +0 -0
  17. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/client.py +0 -0
  18. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/commands.py +0 -0
  19. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/controls.py +0 -0
  20. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/fixtures.py +0 -0
  21. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/personas.py +0 -0
  22. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/requests.py +0 -0
  23. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/copilot/skills.py +0 -0
  24. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/__init__.py +0 -0
  25. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/errors.py +0 -0
  26. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/evals.py +0 -0
  27. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/plugin.py +0 -0
  28. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/prompt.py +0 -0
  29. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/result.py +0 -0
  30. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/serialization.py +0 -0
  31. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/skill.py +0 -0
  32. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/skill_evals.py +0 -0
  33. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/skill_grading.py +0 -0
  34. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/core/validation.py +0 -0
  35. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/execution/__init__.py +0 -0
  36. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/execution/rate_limiter.py +0 -0
  37. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/execution/servers.py +0 -0
  38. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/execution/skill_tools.py +0 -0
  39. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/fixtures/__init__.py +0 -0
  40. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/fixtures/factories.py +0 -0
  41. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/fixtures/iteration.py +0 -0
  42. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/onboarding.py +0 -0
  43. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/plugin.py +0 -0
  44. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/plugin_options.py +0 -0
  45. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/plugin_report.py +0 -0
  46. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/reporting/__init__.py +0 -0
  47. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/reporting/collector.py +0 -0
  48. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/reporting/generator.py +0 -0
  49. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/reporting/schema.py +0 -0
  50. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/__init__.py +0 -0
  51. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/banking.py +0 -0
  52. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/banking_mcp.py +0 -0
  53. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/todo.py +0 -0
  54. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/todo_mcp.py +0 -0
  55. {pytest_copilot-2.0.0 → pytest_copilot-2.1.0}/src/pytest_copilot/testing/types.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pytest-copilot
3
- Version: 2.0.0
3
+ Version: 2.1.0
4
4
  Summary: Run GitHub Copilot tasks in pytest. Check results with your own assertions.
5
5
  Project-URL: Homepage, https://github.com/sbroenne/pytest-copilot
6
6
  Project-URL: Repository, https://github.com/sbroenne/pytest-copilot
@@ -22,13 +22,13 @@ Requires-Python: >=3.11
22
22
  Requires-Dist: github-copilot-sdk>=1.0.28
23
23
  Requires-Dist: httpx>=0.28.1
24
24
  Requires-Dist: mcp>=2.3.0
25
- Requires-Dist: pydantic>=2.14.1
26
- Requires-Dist: pytest-asyncio>=1.4.1
25
+ Requires-Dist: pydantic>=2.14.2
26
+ Requires-Dist: pytest-asyncio>=1.4.1.post1
27
27
  Requires-Dist: pytest>=9.2.0
28
28
  Requires-Dist: python-frontmatter>=1.3.0
29
29
  Requires-Dist: tomlkit>=0.15.2
30
- Requires-Dist: trio>=0.34.0
31
- Requires-Dist: websockets>=17.3
30
+ Requires-Dist: trio>=0.35.0
31
+ Requires-Dist: websockets>=17.4
32
32
  Provides-Extra: dev
33
33
  Requires-Dist: pre-commit>=4.7.0; extra == 'dev'
34
34
  Requires-Dist: pyright>=1.1.414; extra == 'dev'
@@ -38,7 +38,7 @@ Requires-Dist: ruff>=0.17.3; extra == 'dev'
38
38
  Requires-Dist: typeguard>=4.6.0; extra == 'dev'
39
39
  Provides-Extra: docs
40
40
  Requires-Dist: cairosvg>=2.9.1; extra == 'docs'
41
- Requires-Dist: mkdocs-material<9.9,>=9.7.7; extra == 'docs'
41
+ Requires-Dist: mkdocs-material<9.9,>=9.8.0; extra == 'docs'
42
42
  Requires-Dist: mkdocs>=1.6.1; extra == 'docs'
43
43
  Requires-Dist: mkdocstrings[python]>=1.0.8; extra == 'docs'
44
44
  Requires-Dist: pillow>=13.0.0; extra == 'docs'
@@ -46,7 +46,7 @@ Provides-Extra: test
46
46
  Requires-Dist: syrupy<7,>=6.1.1; extra == 'test'
47
47
  Description-Content-Type: text/markdown
48
48
 
49
- # pytest-copilot
49
+ # pytest-copilot - pytest for GitHub Copilot
50
50
 
51
51
  [![PyPI version](https://img.shields.io/pypi/v/pytest-copilot)](https://pypi.org/project/pytest-copilot/)
52
52
  [![CI](https://github.com/sbroenne/pytest-copilot/actions/workflows/ci.yml/badge.svg)](https://github.com/sbroenne/pytest-copilot/actions/workflows/ci.yml)
@@ -56,13 +56,13 @@ Description-Content-Type: text/markdown
56
56
 
57
57
  Independently maintained; not an official GitHub product or endorsed by GitHub.
58
58
 
59
- pytest-copilot runs real Copilot sessions from pytest. Give Copilot a
59
+ pytest-copilot runs real GitHub Copilot sessions from pytest. Give GitHub Copilot a
60
60
  task, check the actual output with ordinary assertions, and save the execution
61
61
  as JSON.
62
62
 
63
63
  Use it to test MCP servers, CLI tools, skills, system prompts, plugins, and custom
64
64
  agents. It answers a different question from your tool's unit tests: **can
65
- Copilot use the interface correctly?** A working tool can still have confusing
65
+ GitHub Copilot use the interface correctly?** A working tool can still have confusing
66
66
  descriptions or arguments that lead the agent to the wrong result.
67
67
 
68
68
  You define what correctness means. The framework manages the Copilot session,
@@ -88,6 +88,9 @@ and adds starter-model rates to `pricing.toml`. It reports conflicts rather than
88
88
  overwriting existing files or settings. `doctor` checks setup and Copilot access.
89
89
  Real task execution may consume Copilot premium requests.
90
90
 
91
+ For installation from a downloaded package instead of PyPI, see
92
+ [install from a release download](docs/getting-started/index.md#install-from-a-release-download).
93
+
91
94
  The test checks the tool's arguments and returned task state. pytest prints the
92
95
  result; `aitest-reports/results.json` preserves the execution. See the
93
96
  [setup guide](docs/getting-started/index.md) or the standalone
@@ -1,4 +1,4 @@
1
- # pytest-copilot
1
+ # pytest-copilot - pytest for GitHub Copilot
2
2
 
3
3
  [![PyPI version](https://img.shields.io/pypi/v/pytest-copilot)](https://pypi.org/project/pytest-copilot/)
4
4
  [![CI](https://github.com/sbroenne/pytest-copilot/actions/workflows/ci.yml/badge.svg)](https://github.com/sbroenne/pytest-copilot/actions/workflows/ci.yml)
@@ -8,13 +8,13 @@
8
8
 
9
9
  Independently maintained; not an official GitHub product or endorsed by GitHub.
10
10
 
11
- pytest-copilot runs real Copilot sessions from pytest. Give Copilot a
11
+ pytest-copilot runs real GitHub Copilot sessions from pytest. Give GitHub Copilot a
12
12
  task, check the actual output with ordinary assertions, and save the execution
13
13
  as JSON.
14
14
 
15
15
  Use it to test MCP servers, CLI tools, skills, system prompts, plugins, and custom
16
16
  agents. It answers a different question from your tool's unit tests: **can
17
- Copilot use the interface correctly?** A working tool can still have confusing
17
+ GitHub Copilot use the interface correctly?** A working tool can still have confusing
18
18
  descriptions or arguments that lead the agent to the wrong result.
19
19
 
20
20
  You define what correctness means. The framework manages the Copilot session,
@@ -40,6 +40,9 @@ and adds starter-model rates to `pricing.toml`. It reports conflicts rather than
40
40
  overwriting existing files or settings. `doctor` checks setup and Copilot access.
41
41
  Real task execution may consume Copilot premium requests.
42
42
 
43
+ For installation from a downloaded package instead of PyPI, see
44
+ [install from a release download](docs/getting-started/index.md#install-from-a-release-download).
45
+
43
46
  The test checks the tool's arguments and returned task state. pytest prints the
44
47
  result; `aitest-reports/results.json` preserves the execution. See the
45
48
  [setup guide](docs/getting-started/index.md) or the standalone
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["hatchling>=1.32.4"]
2
+ requires = ["hatchling>=1.33.0"]
3
3
  build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pytest-copilot"
7
- version = "2.0.0"
7
+ version = "2.1.0"
8
8
  description = "Run GitHub Copilot tasks in pytest. Check results with your own assertions."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -28,14 +28,14 @@ classifiers = [
28
28
  dependencies = [
29
29
  "pytest>=9.2.0",
30
30
  "mcp>=2.3.0",
31
- "pydantic>=2.14.1",
31
+ "pydantic>=2.14.2",
32
32
  "python-frontmatter>=1.3.0",
33
33
  "github-copilot-sdk>=1.0.28",
34
34
  "httpx>=0.28.1",
35
- "trio>=0.34.0",
35
+ "trio>=0.35.0",
36
36
  "tomlkit>=0.15.2",
37
- "pytest-asyncio>=1.4.1",
38
- "websockets>=17.3",
37
+ "pytest-asyncio>=1.4.1.post1",
38
+ "websockets>=17.4",
39
39
  ]
40
40
 
41
41
  [project.optional-dependencies]
@@ -52,7 +52,7 @@ test = [
52
52
  ]
53
53
  docs = [
54
54
  "mkdocs>=1.6.1",
55
- "mkdocs-material>=9.7.7,<9.9",
55
+ "mkdocs-material>=9.8.0,<9.9",
56
56
  "mkdocstrings[python]>=1.0.8",
57
57
  "pillow>=13.0.0",
58
58
  "cairosvg>=2.9.1",
@@ -27,6 +27,9 @@ def snapshot_session_configuration(
27
27
  "model": session_config.get("model"),
28
28
  "instructions": system.get("content"),
29
29
  "system_message_mode": system.get("mode"),
30
+ "response_schema": (
31
+ agent.response_schema.model_json_schema() if agent.response_schema is not None else None
32
+ ),
30
33
  "reasoning_effort": session_config.get("reasoning_effort"),
31
34
  "client_mode": agent.client_mode,
32
35
  "image_detail": agent.image_detail,
@@ -6,6 +6,7 @@ from collections.abc import Awaitable, Callable, Mapping
6
6
  from typing import Any, Literal, Protocol, TypeAlias
7
7
 
8
8
  from copilot.session import CustomAgentConfig, MCPServerConfig, ReasoningEffort, SessionHooks
9
+ from pydantic import BaseModel
9
10
 
10
11
  from pytest_copilot.copilot.result import CopilotResult, CopilotResultAgent
11
12
 
@@ -54,6 +55,10 @@ class CopilotEventMapper(Protocol):
54
55
  class CopilotTaskConfig(CopilotResultAgent, Protocol):
55
56
  """Configuration surface consumed by the runner and personas."""
56
57
 
58
+ @property
59
+ def response_schema(self) -> type[BaseModel] | None:
60
+ raise NotImplementedError
61
+
57
62
  @property
58
63
  def client_mode(self) -> Literal["copilot-cli", "empty"]:
59
64
  raise NotImplementedError
@@ -3,7 +3,7 @@
3
3
  Converts the raw event stream from the Copilot SDK into structured
4
4
  Turn/ToolCall objects for assertion and reporting.
5
5
 
6
- SDK Event Types (38 values) grouped by what they map to:
6
+ SDK event types grouped by what they map to:
7
7
 
8
8
  Tool lifecycle:
9
9
  tool.execution_start → Start tracking a ToolCall
@@ -32,7 +32,8 @@ SDK Event Types (38 values) grouped by what they map to:
32
32
  session.resume → Session resumed
33
33
  session.idle → Eval finished processing
34
34
  session.error → Error occurred
35
- session.shutdown → Session terminated; carries premium request count
35
+ session.usage_checkpoint → Cumulative premium request count
36
+ session.shutdown → Final cumulative premium request count, when emitted
36
37
  session.info → Informational message
37
38
  session.model_change → Model changed mid-session
38
39
  session.usage_info → Context-window usage (tokens/limit; no premium requests)
@@ -558,27 +559,16 @@ class EventMapper:
558
559
  SDK 1.x's ``session.usage_info`` no longer carries a premium-request
559
560
  count (it's context-window stats only). Retained as a documented
560
561
  no-op handler so the event isn't logged as unhandled; see
561
- ``_handle_session_shutdown`` for premium requests.
562
+ ``_handle_session_accounting`` for premium requests.
562
563
  """
563
564
 
564
- def _handle_session_shutdown(self, event: SessionEvent) -> None:
565
- """Handle session shutdown — capture the total premium request count.
566
-
567
- KNOWN GAP (verified with SDK 1.0.13): ``_total_premium_requests`` exists on
568
- ``SessionShutdownData`` per the generated schema, but empirically
569
- ``session.shutdown`` is never delivered to ``session.on()`` listeners
570
- via the ``client.stop()`` teardown path this runner uses. The live
571
- event integration test recorded zero shutdown events even with
572
- its listener registered before session creation. So ``premium_requests``
573
- stays 0.0 in practice today. This handler is kept because it's
574
- schema-correct and harmless, in case a future SDK version emits the
575
- event (or an alternate teardown path does). If this still reads 0.0
576
- after upgrading github-copilot-sdk, check whether the SDK now
577
- exposes a public usage/metrics RPC instead of relying on this event.
578
- """
579
- self._total_premium_requests = float(
580
- _get_data_field(event, "_total_premium_requests", 0) or 0
581
- )
565
+ def _handle_session_accounting(self, event: SessionEvent) -> None:
566
+ """Capture cumulative totals without adding repeated checkpoints."""
567
+ if getattr(event, "agent_id", None):
568
+ return
569
+ reported = _get_data_field(event, "_total_premium_requests", None)
570
+ if reported is not None:
571
+ self._total_premium_requests = max(self._total_premium_requests, float(reported))
582
572
 
583
573
  def _handle_session_error(self, event: SessionEvent) -> None:
584
574
  """Handle session error."""
@@ -786,7 +776,8 @@ _EVENT_HANDLERS: dict[str, Any] = {
786
776
  "session.start": EventMapper._handle_session_start,
787
777
  "session.error": EventMapper._handle_session_error,
788
778
  "session.usage_info": EventMapper._handle_session_usage_info,
789
- "session.shutdown": EventMapper._handle_session_shutdown,
779
+ "session.usage_checkpoint": EventMapper._handle_session_accounting,
780
+ "session.shutdown": EventMapper._handle_session_accounting,
790
781
  "abort": EventMapper._handle_abort,
791
782
  # User
792
783
  "user.message": EventMapper._handle_user_message,
@@ -86,7 +86,7 @@ class CopilotResult:
86
86
  # Model actually used (from session.start or assistant.usage)
87
87
  model_used: str | None = None
88
88
 
89
- # Premium requests (from session.usage_info — CopilotTask only)
89
+ # Cumulative premium requests from SDK usage checkpoints and shutdown.
90
90
  total_premium_requests: float = 0.0
91
91
 
92
92
  # Raw SDK events for advanced inspection
@@ -156,7 +156,12 @@ async def run_copilot(agent: CopilotTaskConfig, prompt: str) -> CopilotResult:
156
156
  skill_discovery,
157
157
  )
158
158
  send_started = True
159
- await session.send_and_wait(prompt, timeout=agent.timeout_s)
159
+ if agent.response_schema is None:
160
+ await session.send_and_wait(prompt, timeout=agent.timeout_s)
161
+ else:
162
+ await session.send_and_wait_typed(
163
+ prompt, agent.response_schema, timeout=agent.timeout_s
164
+ )
160
165
 
161
166
  execution = asyncio.create_task(execute())
162
167
  watchers = [
@@ -6,6 +6,8 @@ from dataclasses import dataclass, field, replace
6
6
  from pathlib import Path
7
7
  from typing import Any, Literal, cast
8
8
 
9
+ from pydantic import BaseModel
10
+
9
11
  from pytest_copilot.copilot.contracts import (
10
12
  CopilotCustomAgentConfig,
11
13
  CopilotMCPServerConfig,
@@ -68,6 +70,10 @@ class CopilotTask:
68
70
  advisory for the top-level session (it is *not* hard-enforced mid-run)
69
71
  and is used when configuring subagent turn caps.
70
72
 
73
+ ``response_schema`` is an optional Pydantic model class checked by the
74
+ SDK when sending the task. It is not a session-creation setting and
75
+ is not inherited by framework-owned child sessions.
76
+
71
77
  Example:
72
78
  # Minimal
73
79
  CopilotTask()
@@ -103,6 +109,7 @@ class CopilotTask:
103
109
  # appended to (or replacing) the CLI's built-in system message.
104
110
  instructions: str | None = None
105
111
  system_message_mode: Literal["append", "replace"] = "append"
112
+ response_schema: type[BaseModel] | None = None
106
113
 
107
114
  # Context
108
115
  working_directory: str | None = None
@@ -150,6 +157,11 @@ class CopilotTask:
150
157
  persona: CopilotPersona = field(default_factory=_default_persona)
151
158
 
152
159
  def __post_init__(self) -> None:
160
+ if self.response_schema is not None and (
161
+ not isinstance(self.response_schema, type)
162
+ or not issubclass(self.response_schema, BaseModel)
163
+ ):
164
+ raise TypeError("response_schema must be a Pydantic model class or None")
153
165
  if self.client_mode not in ("copilot-cli", "empty"):
154
166
  raise ValueError("client_mode must be 'copilot-cli' or 'empty'")
155
167
  if self.image_detail not in (None, "auto", "low", "high"):
@@ -283,6 +295,7 @@ class CopilotTask:
283
295
  allowed_tools=allowed_tools,
284
296
  excluded_tools=None,
285
297
  mcp_servers=mcp_servers,
298
+ response_schema=None,
286
299
  active_agent=None,
287
300
  custom_agents=[
288
301
  agent for agent in self.custom_agents if require_custom_agent_name(agent) != name
@@ -30,23 +30,30 @@ models_without_pricing: set[str] = set()
30
30
 
31
31
  Pricing = tuple[float, float, float]
32
32
  PricingTable = dict[str, Pricing]
33
- PricingCacheKey = tuple[Path, int | None]
33
+ PricingCacheKey = tuple[Path, str | None]
34
34
 
35
35
 
36
36
  @dataclass(slots=True)
37
37
  class _PricingCache:
38
- """Pricing tables keyed by resolved file identity and modification time."""
38
+ """Parsed pricing tables keyed by resolved file identity and contents."""
39
39
 
40
40
  tables: dict[PricingCacheKey, PricingTable] = field(default_factory=dict)
41
41
 
42
42
  def load(self, current_dir: Path) -> PricingTable:
43
43
  toml_path = _find_pricing_toml(current_dir)
44
- cache_key = _pricing_cache_key(current_dir, toml_path)
44
+ if toml_path is None:
45
+ return self.tables.setdefault((current_dir, None), {})
46
+ try:
47
+ content = toml_path.read_text(encoding="utf-8")
48
+ except (OSError, UnicodeDecodeError):
49
+ _logger.warning("Failed to read %s; ignoring", toml_path, exc_info=True)
50
+ return {}
51
+ cache_key = (toml_path.resolve(), content)
45
52
  cached = self.tables.get(cache_key)
46
53
  if cached is not None:
47
54
  return cached
48
55
 
49
- overrides = _read_pricing_file(toml_path)
56
+ overrides = _parse_pricing_file(toml_path, content)
50
57
  self.tables[cache_key] = overrides
51
58
  return overrides
52
59
 
@@ -68,16 +75,14 @@ def _load_user_overrides() -> PricingTable:
68
75
  return _pricing_cache.load(current_dir)
69
76
 
70
77
 
71
- def _read_pricing_file(toml_path: Path | None) -> PricingTable:
72
- """Parse a pricing file into per-million-token rates."""
78
+ def _parse_pricing_file(toml_path: Path, content: str) -> PricingTable:
79
+ """Parse the pricing contents used to identify the cached table."""
73
80
  overrides: PricingTable = {}
74
- if toml_path is None:
75
- return overrides
76
81
 
77
82
  import tomllib
78
83
 
79
84
  try:
80
- raw = tomllib.loads(toml_path.read_text(encoding="utf-8"))
85
+ raw = tomllib.loads(content)
81
86
  models_section: dict[str, Any] = raw.get("models", {})
82
87
  for key, value in models_section.items():
83
88
  if isinstance(value, dict):
@@ -93,8 +98,6 @@ def _read_pricing_file(toml_path: Path | None) -> PricingTable:
93
98
  )
94
99
  except (
95
100
  AttributeError,
96
- OSError,
97
- UnicodeDecodeError,
98
101
  ValueError,
99
102
  TypeError,
100
103
  tomllib.TOMLDecodeError,
@@ -104,14 +107,6 @@ def _read_pricing_file(toml_path: Path | None) -> PricingTable:
104
107
  return overrides
105
108
 
106
109
 
107
- def _pricing_cache_key(current_dir: Path, toml_path: Path | None) -> PricingCacheKey:
108
- """Build a cache key scoped to the active cwd and pricing file version."""
109
- if toml_path is None:
110
- return current_dir, None
111
- stat = toml_path.stat()
112
- return toml_path.resolve(), stat.st_mtime_ns
113
-
114
-
115
110
  def _find_pricing_toml(current_dir: Path) -> Path | None:
116
111
  """Walk upward from cwd looking for ``pricing.toml``."""
117
112
  for parent in (current_dir, *current_dir.parents):
File without changes