pydantic-claude-code 0.7.1__tar.gz → 0.7.2__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 (37) hide show
  1. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/PKG-INFO +2 -2
  2. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/README.md +1 -1
  3. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/pyproject.toml +1 -1
  4. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__init__.py +1 -1
  5. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/model.py +31 -23
  6. pydantic_claude_code-0.7.2/tests/test_model.py +94 -0
  7. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/uv.lock +1 -1
  8. pydantic_claude_code-0.7.1/tests/test_model.py +0 -59
  9. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/.github/workflows/ci.yml +0 -0
  10. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/.github/workflows/publish.yml +0 -0
  11. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/.gitignore +0 -0
  12. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/LICENSE +0 -0
  13. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/examples/basic.py +0 -0
  14. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/install.sh +0 -0
  15. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/scripts/sync_gist.sh +0 -0
  16. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/__main__.py +0 -0
  17. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/auth.py +0 -0
  18. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/clai2.py +0 -0
  19. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/config.py +0 -0
  20. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/credentials.py +0 -0
  21. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/flow.py +0 -0
  22. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/provider.py +0 -0
  23. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/py.typed +0 -0
  24. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/storage.py +0 -0
  25. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/src/pydantic_ai_claude_code/updates.py +0 -0
  26. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/conftest.py +0 -0
  27. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_callback_server.py +0 -0
  28. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_clai2.py +0 -0
  29. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_credentials.py +0 -0
  30. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_flow.py +0 -0
  31. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_install.py +0 -0
  32. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_integration.py +0 -0
  33. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_keyring_store.py +0 -0
  34. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_provider.py +0 -0
  35. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_refresh.py +0 -0
  36. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/tests/test_storage.py +0 -0
  37. {pydantic_claude_code-0.7.1 → pydantic_claude_code-0.7.2}/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.1
3
+ Version: 0.7.2
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/
@@ -336,7 +336,7 @@ uv run pytest
336
336
 
337
337
  To release, bump `version` in `pyproject.toml` and `__version__` in
338
338
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
339
- push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
339
+ push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). The `Publish` workflow tests,
340
340
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
341
341
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
342
342
  update notice install from.
@@ -307,7 +307,7 @@ uv run pytest
307
307
 
308
308
  To release, bump `version` in `pyproject.toml` and `__version__` in
309
309
  `src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
310
- push a matching tag (`git tag v0.7.1 && git push origin v0.7.1`). The `Publish` workflow tests,
310
+ push a matching tag (`git tag v0.7.2 && git push origin v0.7.2`). The `Publish` workflow tests,
311
311
  builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret. Then run
312
312
  `scripts/sync_gist.sh` to publish the release to the install gist, which is what the one-liner and the
313
313
  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.1"
7
+ version = "0.7.2"
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.1"
29
+ __version__ = "0.7.2"
30
30
  """Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
31
31
 
32
32
 
@@ -1,4 +1,4 @@
1
- """The Claude Code model: an `AnthropicModel` with the Claude Code persona prepended."""
1
+ """The Claude Code model: an `AnthropicModel` whose system prompt always opens with the Claude Code persona."""
2
2
 
3
3
  from __future__ import annotations
4
4
 
@@ -6,9 +6,10 @@ from collections.abc import AsyncGenerator, Iterator
6
6
  from contextlib import asynccontextmanager, contextmanager
7
7
  from typing import Any
8
8
 
9
+ from anthropic.types.beta import BetaMessageParam, BetaTextBlockParam
9
10
  from pydantic_ai import RunContext
10
11
  from pydantic_ai.exceptions import ModelAPIError
11
- from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart
12
+ from pydantic_ai.messages import ModelMessage, ModelResponse
12
13
  from pydantic_ai.models import ModelRequestParameters, StreamedResponse
13
14
  from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
14
15
  from pydantic_ai.providers import Provider
@@ -21,10 +22,8 @@ from .auth import ClaudeCodeSignInExpiredError
21
22
  class ClaudeCodeModel(AnthropicModel):
22
23
  """AnthropicModel whose system prompt opens with the Claude Code persona.
23
24
 
24
- The subscription backend expects the Claude Code persona at position 0 of
25
- the system context. Prepending a `SystemPromptPart` here is idempotent:
26
- once it's in history it stays, and repeated `prepare_messages` calls don't
27
- duplicate it.
25
+ The subscription backend expects the persona as the first `system` block, on its own. That is enforced
26
+ on every request as it is built, not in message history, which compaction rewrites: see `_persona_first`.
28
27
  """
29
28
 
30
29
  def __init__(
@@ -51,12 +50,14 @@ class ClaudeCodeModel(AnthropicModel):
51
50
  )
52
51
  super().__init__(model_name, provider=provider, settings={**defaults, **(settings or {})}, **kwargs)
53
52
 
54
- def prepare_messages(
53
+ async def _map_message(
55
54
  self,
56
55
  messages: list[ModelMessage],
57
- model_request_parameters=None,
58
- ) -> list[ModelMessage]:
59
- return super().prepare_messages(_prepend_persona(messages), model_request_parameters)
56
+ model_request_parameters: ModelRequestParameters,
57
+ model_settings: AnthropicModelSettings,
58
+ ) -> tuple[str | list[BetaTextBlockParam], list[BetaMessageParam]]:
59
+ system, anthropic_messages = await super()._map_message(messages, model_request_parameters, model_settings)
60
+ return _persona_first(system), anthropic_messages
60
61
 
61
62
  async def request(
62
63
  self,
@@ -96,16 +97,23 @@ def _surface_expired_sign_in() -> Iterator[None]:
96
97
  raise
97
98
 
98
99
 
99
- def _prepend_persona(messages: list[ModelMessage]) -> list[ModelMessage]:
100
- """Return `messages` with the persona added first, unless it's already there."""
101
- for index, message in enumerate(messages):
102
- if not isinstance(message, ModelRequest):
103
- continue
104
- if any(
105
- isinstance(part, SystemPromptPart) and part.content.strip().startswith(config.CLAUDE_CODE_SYSTEM_PROMPT)
106
- for part in message.parts
107
- ):
108
- return messages
109
- updated = ModelRequest([SystemPromptPart(config.CLAUDE_CODE_SYSTEM_PROMPT), *message.parts])
110
- return [*messages[:index], updated, *messages[index + 1 :]]
111
- return messages
100
+ def _persona_first(system: str | list[BetaTextBlockParam]) -> list[BetaTextBlockParam]:
101
+ """`system` as blocks, the first being the persona alone and no other block repeating it.
102
+
103
+ History cannot be trusted to keep the persona in place: `AnthropicModel` joins all of a run's opening
104
+ `SystemPromptPart`s into one block, and compaction rewrites them, which once left a conversation summary
105
+ inside the persona's block. So every request is fixed up here, whatever its history holds. A cache
106
+ breakpoint on a block that held only the persona stays with the persona.
107
+ """
108
+ persona = BetaTextBlockParam(type="text", text=config.CLAUDE_CODE_SYSTEM_PROMPT)
109
+ rest: list[BetaTextBlockParam] = []
110
+ for block in [BetaTextBlockParam(type="text", text=system)] if isinstance(system, str) else system:
111
+ pieces = (piece.strip() for piece in block["text"].split(config.CLAUDE_CODE_SYSTEM_PROMPT))
112
+ text = "\n\n".join(piece for piece in pieces if piece)
113
+ if text:
114
+ kept = block.copy()
115
+ kept["text"] = text
116
+ rest.append(kept)
117
+ elif "cache_control" in block:
118
+ (rest[-1] if rest else persona)["cache_control"] = block["cache_control"]
119
+ return [persona, *rest]
@@ -0,0 +1,94 @@
1
+ """`ClaudeCodeModel`: its caching default, and the persona every request opens its system prompt with."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import timedelta
6
+ from typing import Any
7
+
8
+ import pytest
9
+ from anthropic.types.beta import BetaTextBlockParam
10
+ from pydantic_ai import Agent
11
+ from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart, TextPart, UserPromptPart
12
+ from pydantic_ai.models.anthropic import AnthropicModelSettings
13
+ from pydantic_ai.providers.anthropic import AnthropicProvider
14
+
15
+ from conftest import MessagesServer
16
+ from pydantic_ai_claude_code import config
17
+ from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
18
+ from pydantic_ai_claude_code.model import ClaudeCodeModel, _persona_first
19
+ from pydantic_ai_claude_code.provider import ClaudeCodeProvider
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ ("settings", "expected"),
24
+ [
25
+ (None, timedelta(hours=1)),
26
+ (AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
27
+ (AnthropicModelSettings(anthropic_cache=False), None),
28
+ (AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
29
+ ],
30
+ )
31
+ def test_cache_retention_defaults_to_one_hour(
32
+ settings: AnthropicModelSettings | None, expected: timedelta | None
33
+ ) -> None:
34
+ model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
35
+ assert model.resolve_cache_retention(None) == expected
36
+ assert model.resolve_cache_retention(
37
+ AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
38
+ ) == timedelta(minutes=5)
39
+
40
+
41
+ PERSONA = config.CLAUDE_CODE_SYSTEM_PROMPT
42
+ SUMMARY = "Summary of previous conversation:\n\n## Intent\nShip the plugin."
43
+
44
+
45
+ async def _sent_system(
46
+ messages_stub: MessagesServer, history: list[ModelMessage], **agent: Any
47
+ ) -> list[dict[str, Any]]:
48
+ """The `system` blocks the subscription backend receives for a run continuing `history`."""
49
+ provider = ClaudeCodeProvider(
50
+ ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh"), base_url=messages_stub.url
51
+ )
52
+ await Agent(ClaudeCodeModel("claude-opus-5-5", provider=provider), **agent).run("go on", message_history=history)
53
+ system = messages_stub.received["system"]
54
+ assert isinstance(system, list)
55
+ return system # type: ignore[return-value]
56
+
57
+
58
+ def _texts(system: list[dict[str, Any]]) -> list[str]:
59
+ return [block["text"] for block in system]
60
+
61
+
62
+ @pytest.mark.parametrize(
63
+ "parts",
64
+ [
65
+ pytest.param([SystemPromptPart(f"{PERSONA}\n\n{SUMMARY}")], id="summary-inside-the-persona-part"),
66
+ pytest.param([SystemPromptPart(PERSONA), SystemPromptPart(SUMMARY)], id="joined-into-one-block"),
67
+ pytest.param([SystemPromptPart(SUMMARY), SystemPromptPart(PERSONA)], id="summary-before-the-persona"),
68
+ pytest.param([SystemPromptPart(SUMMARY)], id="compaction-dropped-the-persona"),
69
+ ],
70
+ )
71
+ async def test_compacted_history_still_sends_the_persona_alone_first(
72
+ messages_stub: MessagesServer, parts: list[SystemPromptPart]
73
+ ) -> None:
74
+ history: list[ModelMessage] = [ModelRequest([*parts, UserPromptPart("earlier")]), ModelResponse([TextPart("ok")])]
75
+ system = await _sent_system(messages_stub, history)
76
+ assert _texts(system) == [PERSONA, SUMMARY]
77
+
78
+
79
+ async def test_instructions_follow_the_persona_and_keep_their_cache_breakpoint(messages_stub: MessagesServer) -> None:
80
+ settings = AnthropicModelSettings(anthropic_cache_instructions="1h")
81
+ system = await _sent_system(messages_stub, [], instructions="Be terse.", model_settings=settings)
82
+ assert _texts(system) == [PERSONA, "Be terse."]
83
+ assert system[-1]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}, "the breakpoint caches the persona too"
84
+
85
+
86
+ async def test_a_fresh_run_without_any_system_prompt_gets_just_the_persona(messages_stub: MessagesServer) -> None:
87
+ assert _texts(await _sent_system(messages_stub, [])) == [PERSONA]
88
+
89
+
90
+ def test_a_cache_breakpoint_on_a_persona_only_block_moves_to_the_persona() -> None:
91
+ cached = BetaTextBlockParam(type="text", text=PERSONA, cache_control={"type": "ephemeral"})
92
+ first, *rest = _persona_first([cached])
93
+ assert first == cached
94
+ assert rest == []
@@ -1430,7 +1430,7 @@ wheels = [
1430
1430
 
1431
1431
  [[package]]
1432
1432
  name = "pydantic-claude-code"
1433
- version = "0.7.1"
1433
+ version = "0.7.2"
1434
1434
  source = { editable = "." }
1435
1435
  dependencies = [
1436
1436
  { name = "keyring" },
@@ -1,59 +0,0 @@
1
- """Tests for the Claude Code persona prepend logic."""
2
-
3
- from __future__ import annotations
4
-
5
- from datetime import timedelta
6
-
7
- import pytest
8
-
9
- from pydantic_ai.messages import ModelMessage, ModelRequest, SystemPromptPart, UserPromptPart
10
- from pydantic_ai.models.anthropic import AnthropicModelSettings
11
- from pydantic_ai.providers.anthropic import AnthropicProvider
12
-
13
- from pydantic_ai_claude_code import config
14
- from pydantic_ai_claude_code.model import ClaudeCodeModel, _prepend_persona
15
-
16
-
17
- @pytest.mark.parametrize(
18
- ("settings", "expected"),
19
- [
20
- (None, timedelta(hours=1)),
21
- (AnthropicModelSettings(anthropic_cache="5m"), timedelta(minutes=5)),
22
- (AnthropicModelSettings(anthropic_cache=False), None),
23
- (AnthropicModelSettings(anthropic_cache_messages="1h"), timedelta(hours=1)),
24
- ],
25
- )
26
- def test_cache_retention_defaults_to_one_hour(
27
- settings: AnthropicModelSettings | None, expected: timedelta | None
28
- ) -> None:
29
- model = ClaudeCodeModel("claude-sonnet-4-6", provider=AnthropicProvider(api_key="test-key"), settings=settings)
30
- assert model.resolve_cache_retention(None) == expected
31
- assert model.resolve_cache_retention(
32
- AnthropicModelSettings(anthropic_cache="5m", anthropic_cache_messages=False)
33
- ) == timedelta(minutes=5)
34
-
35
-
36
- def test_persona_prepended_to_leading_request() -> None:
37
- messages: list[ModelMessage] = [
38
- ModelRequest([SystemPromptPart("You are a helpful assistant."), UserPromptPart("hi")])
39
- ]
40
- out = _prepend_persona(messages)
41
- leading = out[0]
42
- assert isinstance(leading, ModelRequest)
43
- persona, user_system = leading.parts[:2]
44
- assert isinstance(persona, SystemPromptPart)
45
- assert persona.content == config.CLAUDE_CODE_SYSTEM_PROMPT
46
- assert isinstance(user_system, SystemPromptPart)
47
- assert user_system.content == "You are a helpful assistant."
48
- # The user prompt is untouched.
49
- assert leading.parts[2].content == "hi" # type: ignore[attr-defined]
50
-
51
-
52
- def test_persona_prepend_is_idempotent() -> None:
53
- messages: list[ModelMessage] = [ModelRequest([SystemPromptPart("hi")])]
54
- once = _prepend_persona(messages)
55
- twice = _prepend_persona(once)
56
- parts = twice[0].parts # type: ignore[attr-defined]
57
- assert (
58
- sum(1 for p in parts if isinstance(p, SystemPromptPart) and p.content == config.CLAUDE_CODE_SYSTEM_PROMPT) == 1
59
- )