pydantic-claude-code 0.7.2__tar.gz → 0.7.4__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 (36) hide show
  1. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/PKG-INFO +10 -6
  2. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/README.md +9 -5
  3. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/pyproject.toml +1 -1
  4. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/__init__.py +1 -1
  5. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/clai2.py +52 -8
  6. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/flow.py +4 -1
  7. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/model.py +25 -3
  8. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_clai2.py +54 -6
  9. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_flow.py +13 -0
  10. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_model.py +54 -2
  11. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/uv.lock +1 -1
  12. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/.github/workflows/ci.yml +0 -0
  13. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/.github/workflows/publish.yml +0 -0
  14. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/.gitignore +0 -0
  15. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/LICENSE +0 -0
  16. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/examples/basic.py +0 -0
  17. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/install.sh +0 -0
  18. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/scripts/sync_gist.sh +0 -0
  19. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/__main__.py +0 -0
  20. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/auth.py +0 -0
  21. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/config.py +0 -0
  22. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/credentials.py +0 -0
  23. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/provider.py +0 -0
  24. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/py.typed +0 -0
  25. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/storage.py +0 -0
  26. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/src/pydantic_ai_claude_code/updates.py +0 -0
  27. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/conftest.py +0 -0
  28. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_callback_server.py +0 -0
  29. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_credentials.py +0 -0
  30. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_install.py +0 -0
  31. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_integration.py +0 -0
  32. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_keyring_store.py +0 -0
  33. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_provider.py +0 -0
  34. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_refresh.py +0 -0
  35. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_storage.py +0 -0
  36. {pydantic_claude_code-0.7.2 → pydantic_claude_code-0.7.4}/tests/test_updates.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pydantic-claude-code
3
- Version: 0.7.2
3
+ Version: 0.7.4
4
4
  Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
5
5
  Project-URL: Source, https://gist.github.com/mpfaffenberger/bd75c7b424ffdc6d81645bfe7de822d3
6
6
  Project-URL: Homepage, https://pypi.org/project/pydantic-claude-code/
@@ -201,10 +201,14 @@ provider. Instead of a `claude-code:` model string, construct
201
201
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
202
202
  `ClaudeCodeProvider` by default.
203
203
 
204
- `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
205
- `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
206
- `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
207
- Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
204
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default, on the conversation and on the
205
+ static prefix: the tool definitions and the instructions get breakpoints of their own, so a new conversation
206
+ reads the prefix earlier ones cached instead of writing it again at the 1-hour price. Passing any
207
+ `anthropic_cache*` setting to the model replaces this default as a whole: for example
208
+ `settings=AnthropicModelSettings(anthropic_cache="5m")` caches only the conversation, for 5 minutes, and
209
+ `settings=AnthropicModelSettings(anthropic_cache=False)` turns caching off. Per-request settings take precedence
210
+ key by key, so to turn caching off for one request, set `anthropic_cache`, `anthropic_cache_instructions` and
211
+ `anthropic_cache_tool_definitions` to `False`.
208
212
 
209
213
  ### Quick start
210
214
 
@@ -336,7 +340,7 @@ uv run pytest
336
340
 
337
341
  To release, bump `version` in `pyproject.toml` and `__version__` in
338
342
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
339
- push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). The `Publish` workflow tests,
343
+ push a matching tag (`git tag v0.7.4 && git push origin v0.7.4`). The `Publish` workflow tests,
340
344
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
341
345
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
342
346
  update notice install from.
@@ -172,10 +172,14 @@ provider. Instead of a `claude-code:` model string, construct
172
172
  `ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
173
173
  `ClaudeCodeProvider` by default.
174
174
 
175
- `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
176
- `settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
177
- `settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
178
- Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
175
+ `ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default, on the conversation and on the
176
+ static prefix: the tool definitions and the instructions get breakpoints of their own, so a new conversation
177
+ reads the prefix earlier ones cached instead of writing it again at the 1-hour price. Passing any
178
+ `anthropic_cache*` setting to the model replaces this default as a whole: for example
179
+ `settings=AnthropicModelSettings(anthropic_cache="5m")` caches only the conversation, for 5 minutes, and
180
+ `settings=AnthropicModelSettings(anthropic_cache=False)` turns caching off. Per-request settings take precedence
181
+ key by key, so to turn caching off for one request, set `anthropic_cache`, `anthropic_cache_instructions` and
182
+ `anthropic_cache_tool_definitions` to `False`.
179
183
 
180
184
  ### Quick start
181
185
 
@@ -307,7 +311,7 @@ uv run pytest
307
311
 
308
312
  To release, bump `version` in `pyproject.toml` and `__version__` in
309
313
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
310
- push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). The `Publish` workflow tests,
314
+ push a matching tag (`git tag v0.7.4 && git push origin v0.7.4`). The `Publish` workflow tests,
311
315
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
312
316
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
313
317
  update notice install from.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pydantic-claude-code"
7
- version = "0.7.2"
7
+ version = "0.7.4"
8
8
  description = "Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10,<3.15"
@@ -26,7 +26,7 @@ from .model import ClaudeCodeModel
26
26
  from .provider import ClaudeCodeProvider
27
27
  from .storage import ClaudeCodeTokenStore, KeyringTokenStore, default_auth_path, default_store
28
28
 
29
- __version__ = "0.7.2"
29
+ __version__ = "0.7.4"
30
30
  """Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
31
31
 
32
32
 
@@ -21,7 +21,7 @@ import asyncio
21
21
  import dataclasses
22
22
  import importlib
23
23
  import sys
24
- from collections.abc import Callable, Sequence
24
+ from collections.abc import Awaitable, Callable, Sequence
25
25
  from datetime import datetime
26
26
  from typing import IO, Any, cast, get_args
27
27
 
@@ -234,10 +234,20 @@ def status(source: ClaudeCodeConfig, profile: str | None = None) -> str:
234
234
  return f"Signed in to {_account(profile)}; tokens are kept in {where}."
235
235
 
236
236
 
237
- async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None], profile: str | None = None) -> str:
237
+ ReadPasteback = Callable[[], Awaitable[str | None]]
238
+ """Reads the address the browser ended on; `None` when the user cancels."""
239
+
240
+
241
+ async def sign_in(
242
+ source: ClaudeCodeConfig,
243
+ show_url: Callable[[str], None],
244
+ profile: str | None = None,
245
+ *,
246
+ read_pasteback: ReadPasteback,
247
+ ) -> str:
238
248
  """Sign in through the browser, or a pasted redirect address, and save the tokens to the chosen store."""
239
249
  store = source.store(profile)
240
- await login(store=store, on_url=show_url, read_pasteback=lambda: run_worker(read_pasted_url))
250
+ await login(store=store, on_url=show_url, read_pasteback=read_pasteback)
241
251
  first = config.MODELS[0]
242
252
  if profile is not None:
243
253
  return f"Signed in to {_account(profile)}. Run /model {PREFIX}@{profile}:{first}, or any other model."
@@ -245,11 +255,38 @@ async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None], pro
245
255
 
246
256
 
247
257
  PASTE_PROMPT = "Or paste the address your browser ended on, then Enter (Esc cancels): "
258
+ PASTE_AGAIN = "No authorization code in that; paste the whole address, then Enter (Esc cancels): "
259
+
260
+
261
+ def paste_reader(host: PluginHost[Any]) -> ReadPasteback:
262
+ """How this CLAI2 build reads a pasted redirect address under the sign-in URL it just printed.
263
+
264
+ Newer builds draw a live panel, and a full-screen menu worker takes it off the screen, hiding the
265
+ printed URL with it. They offer `line_input.read_line`, which pins the prompt under the transcript
266
+ instead, so the URL stays visible. Older builds print straight to the terminal, where
267
+ `read_pasted_url` draws under the URL.
268
+ """
269
+ try:
270
+ line_input = importlib.import_module("pydantic_clai2.ui.prompt.line_input")
271
+ except ImportError:
272
+ return lambda: run_worker(read_pasted_url)
273
+
274
+ async def read() -> str | None:
275
+ prompt = PASTE_PROMPT
276
+ while (text := await line_input.read_line(prompt, console=host.console, hidden=True)) is not None:
277
+ if parse_pasteback(text) is not None:
278
+ return text
279
+ prompt = PASTE_AGAIN
280
+ return None
281
+
282
+ return read
248
283
 
249
284
 
250
285
  def read_pasted_url(keys: Callable[[], str] = menu_key, output: IO[str] = sys.stdout) -> str | None:
251
286
  """Read a pasted redirect address on one line, under the printed sign-in URL; `None` on Esc.
252
287
 
288
+ For CLAI2 builds without `line_input`: see `paste_reader`.
289
+
253
290
  The address carries the authorization code, so it is counted, not echoed: a long URL would also wrap
254
291
  and break the one-line redraw. `keys` is `run_worker`'s `menu_key`, which turns into `ctrl-c` when the
255
292
  browser's callback wins and `login` cancels this read.
@@ -293,12 +330,18 @@ def sign_out(source: ClaudeCodeConfig, profile: str | None = None) -> str:
293
330
  return f"Signed out of {_account(profile)}. The tokens stay valid at Anthropic until they expire."
294
331
 
295
332
 
296
- async def configure(source: ClaudeCodeConfig, show_url: Callable[[str], None], runners: Runners = TERMINAL) -> str:
333
+ async def configure(
334
+ source: ClaudeCodeConfig,
335
+ show_url: Callable[[str], None],
336
+ runners: Runners = TERMINAL,
337
+ *,
338
+ read_pasteback: ReadPasteback,
339
+ ) -> str:
297
340
  """Open the settings menu until Esc or Save & close."""
298
341
 
299
342
  async def account() -> list[str]:
300
343
  try:
301
- return [await sign_in(source, show_url)]
344
+ return [await sign_in(source, show_url, read_pasteback=read_pasteback)]
302
345
  except UserError as exc:
303
346
  return [str(exc)]
304
347
 
@@ -314,6 +357,7 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
314
357
  super().__init__(host, settings)
315
358
  self.source = ClaudeCodeConfig(settings, host.save_settings)
316
359
  self._providers = Providers()
360
+ self._read_pasteback = paste_reader(host)
317
361
  self._update: asyncio.Task[str | None] | None = None
318
362
  self.provider = ModelProvider(
319
363
  prefix=PREFIX,
@@ -355,10 +399,10 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
355
399
  return await account_usage(provider)
356
400
 
357
401
  async def _sign_in(self) -> str:
358
- return await sign_in(self.source, self._show_url)
402
+ return await sign_in(self.source, self._show_url, read_pasteback=self._read_pasteback)
359
403
 
360
404
  async def _sign_in_profile(self, profile: str) -> str:
361
- return await sign_in(self.source, self._show_url, profile)
405
+ return await sign_in(self.source, self._show_url, profile, read_pasteback=self._read_pasteback)
362
406
 
363
407
  def get_commands(self) -> Sequence[Command]:
364
408
  return (
@@ -384,7 +428,7 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
384
428
  return await asyncio.to_thread(action, self.source, args[1] if len(args) == 2 else None)
385
429
 
386
430
  async def configure(self) -> str:
387
- return await configure(self.source, self._show_url)
431
+ return await configure(self.source, self._show_url, read_pasteback=self._read_pasteback)
388
432
 
389
433
  async def on_session_start(self, event: SessionStart) -> None:
390
434
  """Check PyPI for a newer release in the background, so startup never waits on it."""
@@ -207,12 +207,15 @@ async def login(
207
207
  server = start_login_callback_server()
208
208
  timeout = None if read_pasteback is not None else config.CALLBACK_TIMEOUT
209
209
  callback = asyncio.ensure_future(asyncio.to_thread(server.received.wait, timeout))
210
- paste = asyncio.ensure_future(read_pasteback()) if read_pasteback is not None else None
210
+ paste: asyncio.Future[str | None] | None = None
211
211
  try:
212
212
  redirect_uri = f"{config.REDIRECT_HOST}:{server.server_address[1]}/{config.REDIRECT_PATH}"
213
213
  flow = ClaudeCodeOAuthFlow(redirect_uri=redirect_uri)
214
214
  url = flow.authorization_url()
215
+ # Show the URL before the paste prompt starts: the prompt may take over the screen.
215
216
  on_url(url)
217
+ if read_pasteback is not None:
218
+ paste = asyncio.ensure_future(read_pasteback())
216
219
  # Launch the browser off the event path: on some macOS setups `webbrowser.open`
217
220
  # hangs until the UI settles, which would starve the callback wait below.
218
221
  threading.Thread(target=_open_browser, args=(url,), daemon=True).start()
@@ -18,6 +18,29 @@ from pydantic_ai.settings import ModelSettings
18
18
  from . import config
19
19
  from .auth import ClaudeCodeSignInExpiredError
20
20
 
21
+ _CACHE_SETTINGS = (
22
+ "anthropic_cache",
23
+ "anthropic_cache_instructions",
24
+ "anthropic_cache_tool_definitions",
25
+ "anthropic_cache_messages",
26
+ )
27
+ """The explicit Anthropic cache settings. Any one of them replaces the default caching as a whole."""
28
+
29
+
30
+ def _default_cache_settings(settings: ModelSettings | None) -> AnthropicModelSettings:
31
+ """One-hour caching of the conversation and of the static prefix, unless `settings` choose caching themselves.
32
+
33
+ Pydantic AI's unified `cache` setting, which CLAI sends, puts breakpoints after the tool definitions and the
34
+ instructions, so every new conversation reads that shared prefix instead of writing it again. An explicit
35
+ `anthropic_cache*` setting turns the unified one off, so a default naming only `anthropic_cache` would leave
36
+ just the conversation breakpoint: each new session would write its whole prefix at the one-hour price.
37
+ """
38
+ if settings and any(key in settings for key in _CACHE_SETTINGS):
39
+ return AnthropicModelSettings()
40
+ return AnthropicModelSettings(
41
+ anthropic_cache="1h", anthropic_cache_instructions="1h", anthropic_cache_tool_definitions="1h"
42
+ )
43
+
21
44
 
22
45
  class ClaudeCodeModel(AnthropicModel):
23
46
  """AnthropicModel whose system prompt opens with the Claude Code persona.
@@ -45,10 +68,9 @@ class ClaudeCodeModel(AnthropicModel):
45
68
  from .provider import ClaudeCodeProvider
46
69
 
47
70
  provider = ClaudeCodeProvider()
48
- defaults = AnthropicModelSettings(
49
- anthropic_cache=False if settings and settings.get("anthropic_cache_messages") else "1h",
71
+ super().__init__(
72
+ model_name, provider=provider, settings={**_default_cache_settings(settings), **(settings or {})}, **kwargs
50
73
  )
51
- super().__init__(model_name, provider=provider, settings={**defaults, **(settings or {})}, **kwargs)
52
74
 
53
75
  async def _map_message(
54
76
  self,
@@ -8,6 +8,7 @@ import io
8
8
  import shutil
9
9
  import subprocess
10
10
  import sys
11
+ import types
11
12
  from collections.abc import Awaitable, Callable
12
13
  from dataclasses import dataclass
13
14
  from datetime import datetime, timezone
@@ -100,6 +101,10 @@ async def failing_login(
100
101
  raise UserError("Claude Code OAuth callback timed out.")
101
102
 
102
103
 
104
+ async def no_paste() -> str | None:
105
+ return None
106
+
107
+
103
108
  def pick(value: str) -> MenuResult:
104
109
  return MenuResult(item=MenuItem(value, value=value))
105
110
 
@@ -239,7 +244,9 @@ async def test_the_update_check_can_be_turned_off(
239
244
 
240
245
 
241
246
  async def test_bare_command_opens_the_settings_menu(monkeypatch: pytest.MonkeyPatch) -> None:
242
- async def fake_configure(source: ClaudeCodeConfig, show_url: Callable[[str], None]) -> str:
247
+ async def fake_configure(
248
+ source: ClaudeCodeConfig, show_url: Callable[[str], None], *, read_pasteback: clai2.ReadPasteback
249
+ ) -> str:
243
250
  show_url(URL)
244
251
  return f"menu for {source.settings.credentials}"
245
252
 
@@ -256,7 +263,9 @@ async def test_menu_switches_storage_then_signs_in(monkeypatch: pytest.MonkeyPat
256
263
  source = ClaudeCodeConfig(ClaudeCodeSettings(), saved.append)
257
264
  urls: list[str] = []
258
265
 
259
- message = await configure(source, urls.append, scripted(pick("credentials"), pick("account")))
266
+ message = await configure(
267
+ source, urls.append, scripted(pick("credentials"), pick("account")), read_pasteback=no_paste
268
+ )
260
269
 
261
270
  assert saved == [ClaudeCodeSettings(credentials="file")]
262
271
  assert message.splitlines() == [
@@ -271,8 +280,9 @@ async def test_menu_switches_storage_then_signs_in(monkeypatch: pytest.MonkeyPat
271
280
  async def test_menu_reports_a_failed_sign_in_and_an_untouched_menu(monkeypatch: pytest.MonkeyPatch) -> None:
272
281
  monkeypatch.setattr(clai2, "login", failing_login)
273
282
  source = ClaudeCodeConfig(ClaudeCodeSettings(), lambda settings: None)
274
- assert await configure(source, print, scripted(pick("account"))) == "Claude Code OAuth callback timed out."
275
- assert await configure(source, print, scripted()) == "Claude Code settings unchanged."
283
+ menu = await configure(source, print, scripted(pick("account")), read_pasteback=no_paste)
284
+ assert menu == "Claude Code OAuth callback timed out."
285
+ assert await configure(source, print, scripted(), read_pasteback=no_paste) == "Claude Code settings unchanged."
276
286
 
277
287
 
278
288
  def test_auto_follows_the_env_var_and_explicit_choices_do_not(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -403,13 +413,51 @@ async def test_sign_in_offers_the_paste_reader_to_login(monkeypatch: pytest.Monk
403
413
  store.save(CREDS)
404
414
  return CREDS
405
415
 
416
+ async def pasted() -> str | None:
417
+ return PASTED
418
+
406
419
  monkeypatch.setattr(clai2, "login", pasting_login)
407
- monkeypatch.setattr(clai2, "read_pasted_url", lambda: PASTED)
408
420
  source = ClaudeCodeConfig(ClaudeCodeSettings(), lambda settings: None)
409
- assert (await clai2.sign_in(source, print)).startswith("Signed in to Claude Code.")
421
+ assert (await clai2.sign_in(source, print, read_pasteback=pasted)).startswith("Signed in to Claude Code.")
410
422
  assert offered == [PASTED]
411
423
 
412
424
 
425
+ async def test_builds_with_line_input_read_the_paste_under_the_url(monkeypatch: pytest.MonkeyPatch) -> None:
426
+ """A full-screen worker would hide the printed URL on these builds, so the paste goes through `read_line`."""
427
+ loaded = load()
428
+ answers = iter(["nope", PASTED])
429
+ asked: list[tuple[str, object, bool]] = []
430
+
431
+ async def read_line(prompt: str, *, console: Console, hidden: bool = False) -> str | None:
432
+ asked.append((prompt, console, hidden))
433
+ return next(answers)
434
+
435
+ line_input = types.ModuleType("pydantic_clai2.ui.prompt.line_input")
436
+ line_input.read_line = read_line # type: ignore[attr-defined]
437
+ monkeypatch.setitem(sys.modules, "pydantic_clai2.ui.prompt.line_input", line_input)
438
+ assert await clai2.paste_reader(loaded.host)() == PASTED
439
+ assert asked == [
440
+ (clai2.PASTE_PROMPT, loaded.host.console, True),
441
+ (clai2.PASTE_AGAIN, loaded.host.console, True),
442
+ ]
443
+
444
+
445
+ async def test_a_cancelled_line_input_cancels_the_paste(monkeypatch: pytest.MonkeyPatch) -> None:
446
+ async def read_line(prompt: str, *, console: Console, hidden: bool = False) -> str | None:
447
+ return None
448
+
449
+ line_input = types.ModuleType("pydantic_clai2.ui.prompt.line_input")
450
+ line_input.read_line = read_line # type: ignore[attr-defined]
451
+ monkeypatch.setitem(sys.modules, "pydantic_clai2.ui.prompt.line_input", line_input)
452
+ assert await clai2.paste_reader(load().host)() is None
453
+
454
+
455
+ async def test_older_builds_read_the_paste_in_a_worker(monkeypatch: pytest.MonkeyPatch) -> None:
456
+ monkeypatch.setitem(sys.modules, "pydantic_clai2.ui.prompt.line_input", None)
457
+ monkeypatch.setattr(clai2, "read_pasted_url", lambda: PASTED)
458
+ assert await clai2.paste_reader(load().host)() == PASTED
459
+
460
+
413
461
  @dataclass(frozen=True, kw_only=True)
414
462
  class ProfileProvider(ModelProvider):
415
463
  """`ModelProvider` as a CLAI2 build with auth profiles declares it."""
@@ -6,6 +6,7 @@ import asyncio
6
6
  import json
7
7
  import threading
8
8
  import time
9
+ from collections.abc import Awaitable
9
10
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
10
11
  from urllib.parse import parse_qs, urlsplit
11
12
 
@@ -177,6 +178,18 @@ async def test_login_takes_a_pasted_address_when_the_callback_never_comes(token_
177
178
  assert token_stub.last_body["redirect_uri"] == parse_qs(urlsplit(shown[0]).query)["redirect_uri"][0]
178
179
 
179
180
 
181
+ async def test_login_shows_the_url_before_asking_for_a_paste(token_stub, monkeypatch) -> None:
182
+ monkeypatch.setattr(flow, "_open_browser", lambda url: None)
183
+ shown: list[str] = []
184
+
185
+ def paste() -> Awaitable[str | None]:
186
+ assert shown, "the paste prompt started before the sign-in URL was shown"
187
+ return asyncio.sleep(0, _paste_from(shown[0]))
188
+
189
+ await flow.login(store=_MemoryStore(), on_url=shown.append, read_pasteback=paste)
190
+ assert token_stub.last_body["code"] == "pasted-code"
191
+
192
+
180
193
  async def test_login_cancels_the_paste_read_when_the_browser_gets_through(token_stub, monkeypatch) -> None:
181
194
  monkeypatch.setattr(flow, "_open_browser", lambda url: None)
182
195
  cancelled = asyncio.Event()
@@ -15,7 +15,7 @@ from pydantic_ai.providers.anthropic import AnthropicProvider
15
15
  from conftest import MessagesServer
16
16
  from pydantic_ai_claude_code import config
17
17
  from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
18
- from pydantic_ai_claude_code.model import ClaudeCodeModel, _persona_first
18
+ from pydantic_ai_claude_code.model import ClaudeCodeModel, _default_cache_settings, _persona_first
19
19
  from pydantic_ai_claude_code.provider import ClaudeCodeProvider
20
20
 
21
21
 
@@ -33,11 +33,63 @@ def test_cache_retention_defaults_to_one_hour(
33
33
  ) -> None:
34
34
  model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
35
35
  assert model.resolve_cache_retention(None) == expected
36
+ # Per-request settings win key by key, and the longest active breakpoint sets the retention.
36
37
  assert model.resolve_cache_retention(
37
- AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
38
+ AnthropicModelSettings(
39
+ anthropic_cache="5m",
40
+ anthropic_cache_instructions="5m",
41
+ anthropic_cache_tool_definitions="5m",
42
+ anthropic_cache_messages=False,
43
+ )
38
44
  ) == timedelta(minutes=5)
39
45
 
40
46
 
47
+ ONE_HOUR = {"type": "ephemeral", "ttl": "1h"}
48
+
49
+
50
+ def test_the_default_caches_the_static_prefix_as_well_as_the_conversation() -> None:
51
+ assert _default_cache_settings(None) == AnthropicModelSettings(
52
+ anthropic_cache="1h", anthropic_cache_instructions="1h", anthropic_cache_tool_definitions="1h"
53
+ )
54
+
55
+
56
+ @pytest.mark.parametrize(
57
+ "settings",
58
+ [
59
+ AnthropicModelSettings(anthropic_cache="5m"),
60
+ AnthropicModelSettings(anthropic_cache=False),
61
+ AnthropicModelSettings(anthropic_cache_instructions=False),
62
+ AnthropicModelSettings(anthropic_cache_tool_definitions="5m"),
63
+ AnthropicModelSettings(anthropic_cache_messages="1h"),
64
+ ],
65
+ )
66
+ def test_any_explicit_cache_setting_replaces_the_whole_default(settings: AnthropicModelSettings) -> None:
67
+ model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
68
+ assert model.settings == settings
69
+
70
+
71
+ async def test_a_new_session_marks_the_tools_and_instructions_for_reuse(messages_stub: MessagesServer) -> None:
72
+ """CLAI sends the unified `cache` setting; the plugin's one-hour default must keep its static breakpoints."""
73
+ provider = ClaudeCodeProvider(
74
+ ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh"), base_url=messages_stub.url
75
+ )
76
+ agent = Agent(ClaudeCodeModel("claude-opus-5-5", provider=provider), instructions="Be terse.")
77
+
78
+ @agent.tool_plain
79
+ def lookup(key: str) -> str:
80
+ """Look a key up."""
81
+ return key # pragma: no cover -- the stub never calls tools
82
+
83
+ await agent.run("go on", model_settings={"cache": True})
84
+ body = messages_stub.received
85
+ tools = body["tools"]
86
+ system = body["system"]
87
+ assert isinstance(tools, list) and isinstance(system, list)
88
+ assert tools[-1]["cache_control"] == ONE_HOUR
89
+ assert system[-1]["cache_control"] == ONE_HOUR
90
+ assert body["cache_control"] == ONE_HOUR, "the conversation keeps its moving one-hour breakpoint"
91
+
92
+
41
93
  PERSONA = config.CLAUDE_CODE_SYSTEM_PROMPT
42
94
  SUMMARY = "Summary of previous conversation:\n\n## Intent\nShip the plugin."
43
95
 
@@ -1430,7 +1430,7 @@ wheels = [
1430
1430
 
1431
1431
  [[package]]
1432
1432
  name = "pydantic-claude-code"
1433
- version = "0.7.2"
1433
+ version = "0.7.4"
1434
1434
  source = { editable = "." }
1435
1435
  dependencies = [
1436
1436
  { name = "keyring" },