pydantic-claude-code 0.6.2__tar.gz → 0.7.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.
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/PKG-INFO +24 -7
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/README.md +23 -6
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/install.sh +3 -3
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/pyproject.toml +1 -1
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__init__.py +1 -1
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/auth.py +1 -1
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/clai2.py +78 -36
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/model.py +6 -2
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/storage.py +28 -13
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_clai2.py +78 -7
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_install.py +1 -1
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_keyring_store.py +14 -0
- pydantic_claude_code-0.7.0/tests/test_model.py +59 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_storage.py +8 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/uv.lock +1 -1
- pydantic_claude_code-0.6.2/tests/test_model.py +0 -32
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/.github/workflows/ci.yml +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/.github/workflows/publish.yml +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/.gitignore +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/LICENSE +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/examples/basic.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__main__.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/config.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/credentials.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/flow.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/provider.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/py.typed +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/updates.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/conftest.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_callback_server.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_credentials.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_flow.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_integration.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/tests/test_provider.py +0 -0
- {pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/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.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Use your Claude Code subscription from a Pydantic AI Agent or CLAI2, with full tool support
|
|
5
5
|
Project-URL: Repository, https://github.com/mpfaffenberger/pydantic-ai-claude-code
|
|
6
6
|
Project-URL: Homepage, https://pypi.org/project/pydantic-claude-code/
|
|
@@ -67,7 +67,7 @@ One line installs the latest release of the plugin, and running it again updates
|
|
|
67
67
|
curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
To pin a release, pass its tag (`... | sh -s -- v0.
|
|
70
|
+
To pin a release, pass its tag (`... | sh -s -- v0.7.0`), or pass `main` for
|
|
71
71
|
unreleased changes. The script downloads that version of this repo and copies the `src/pydantic_ai_claude_code` folder into CLAI2's
|
|
72
72
|
plugins folder as `claude_code`, replacing any older copy. Nothing to
|
|
73
73
|
`pip install`: everything the plugin imports (`pydantic-ai` with Anthropic
|
|
@@ -115,7 +115,7 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
|
|
|
115
115
|
|
|
116
116
|
### Sign in
|
|
117
117
|
|
|
118
|
-
Run `/login claude
|
|
118
|
+
Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
|
|
119
119
|
prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
|
|
120
120
|
(over SSH, or a remote box), open that URL on any machine and sign in. The
|
|
121
121
|
browser then ends on a `http://localhost:.../callback?code=...` page that fails
|
|
@@ -125,7 +125,7 @@ Enter. CLAI2 counts the characters instead of echoing the code. Or open the sett
|
|
|
125
125
|
|
|
126
126
|
### Pick a model
|
|
127
127
|
|
|
128
|
-
`/login claude` adds every model in the table above to your model list, so
|
|
128
|
+
`/login claude-code` adds every model in the table above to your model list, so
|
|
129
129
|
`/model` offers them right away, and `/model_settings` sets thinking mode,
|
|
130
130
|
effort, and the rest for each. On an older CLAI2, or for a model that isn't
|
|
131
131
|
listed, open `/add_model` and choose the `claude-code` provider, or type one
|
|
@@ -139,6 +139,17 @@ directly:
|
|
|
139
139
|
Headless runs work the same way:
|
|
140
140
|
`clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
|
|
141
141
|
|
|
142
|
+
### Several accounts
|
|
143
|
+
|
|
144
|
+
On a CLAI2 build with auth profiles, `/login claude-code@NAME` signs in another
|
|
145
|
+
account under the profile `NAME` (lowercase letters, digits, `-` and `_`), and
|
|
146
|
+
`claude-code@NAME:MODEL` runs on it, for example
|
|
147
|
+
`/model claude-code@work:claude-opus-5-5`. Models without `@NAME` keep using
|
|
148
|
+
the default sign-in. Each profile has its own tokens: keyring user name `NAME`,
|
|
149
|
+
or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
|
|
150
|
+
a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
|
|
151
|
+
Older CLAI2 builds ignore profiles.
|
|
152
|
+
|
|
142
153
|
### Settings menu
|
|
143
154
|
|
|
144
155
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -150,7 +161,8 @@ opens it. Every change is saved right away and applies from the next run.
|
|
|
150
161
|
| Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
|
|
151
162
|
|
|
152
163
|
`/claude_code logout` and `/claude_code status` do the
|
|
153
|
-
same without the menu
|
|
164
|
+
same without the menu; add a profile name (`/claude_code logout work`) for
|
|
165
|
+
another account.
|
|
154
166
|
|
|
155
167
|
### Where the sign-in lives
|
|
156
168
|
|
|
@@ -169,7 +181,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
|
|
|
169
181
|
after switching.
|
|
170
182
|
|
|
171
183
|
If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
|
|
172
|
-
expired`, run `/login claude`. If the
|
|
184
|
+
expired`, run `/login claude-code`. If the
|
|
173
185
|
plugin fails to load with `cannot import name 'Plugin' from
|
|
174
186
|
'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
|
|
175
187
|
[Install](#install), or pin plugin 0.5.0.
|
|
@@ -182,6 +194,11 @@ provider. Instead of a `claude-code:` model string, construct
|
|
|
182
194
|
`ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
|
|
183
195
|
`ClaudeCodeProvider` by default.
|
|
184
196
|
|
|
197
|
+
`ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
|
|
198
|
+
`settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
|
|
199
|
+
`settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
|
|
200
|
+
Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
|
|
201
|
+
|
|
185
202
|
### Quick start
|
|
186
203
|
|
|
187
204
|
```python
|
|
@@ -312,7 +329,7 @@ uv run pytest
|
|
|
312
329
|
|
|
313
330
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
314
331
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
315
|
-
push a matching tag (`git tag v0.
|
|
332
|
+
push a matching tag (`git tag v0.7.0 && git push origin v0.7.0`). The `Publish` workflow tests,
|
|
316
333
|
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
317
334
|
|
|
318
335
|
The tests never touch your real keychain or token file. They run against a
|
|
@@ -38,7 +38,7 @@ One line installs the latest release of the plugin, and running it again updates
|
|
|
38
38
|
curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
-
To pin a release, pass its tag (`... | sh -s -- v0.
|
|
41
|
+
To pin a release, pass its tag (`... | sh -s -- v0.7.0`), or pass `main` for
|
|
42
42
|
unreleased changes. The script downloads that version of this repo and copies the `src/pydantic_ai_claude_code` folder into CLAI2's
|
|
43
43
|
plugins folder as `claude_code`, replacing any older copy. Nothing to
|
|
44
44
|
`pip install`: everything the plugin imports (`pydantic-ai` with Anthropic
|
|
@@ -86,7 +86,7 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
|
|
|
86
86
|
|
|
87
87
|
### Sign in
|
|
88
88
|
|
|
89
|
-
Run `/login claude
|
|
89
|
+
Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
|
|
90
90
|
prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
|
|
91
91
|
(over SSH, or a remote box), open that URL on any machine and sign in. The
|
|
92
92
|
browser then ends on a `http://localhost:.../callback?code=...` page that fails
|
|
@@ -96,7 +96,7 @@ Enter. CLAI2 counts the characters instead of echoing the code. Or open the sett
|
|
|
96
96
|
|
|
97
97
|
### Pick a model
|
|
98
98
|
|
|
99
|
-
`/login claude` adds every model in the table above to your model list, so
|
|
99
|
+
`/login claude-code` adds every model in the table above to your model list, so
|
|
100
100
|
`/model` offers them right away, and `/model_settings` sets thinking mode,
|
|
101
101
|
effort, and the rest for each. On an older CLAI2, or for a model that isn't
|
|
102
102
|
listed, open `/add_model` and choose the `claude-code` provider, or type one
|
|
@@ -110,6 +110,17 @@ directly:
|
|
|
110
110
|
Headless runs work the same way:
|
|
111
111
|
`clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
|
|
112
112
|
|
|
113
|
+
### Several accounts
|
|
114
|
+
|
|
115
|
+
On a CLAI2 build with auth profiles, `/login claude-code@NAME` signs in another
|
|
116
|
+
account under the profile `NAME` (lowercase letters, digits, `-` and `_`), and
|
|
117
|
+
`claude-code@NAME:MODEL` runs on it, for example
|
|
118
|
+
`/model claude-code@work:claude-opus-5-5`. Models without `@NAME` keep using
|
|
119
|
+
the default sign-in. Each profile has its own tokens: keyring user name `NAME`,
|
|
120
|
+
or the file `auth-NAME.json` next to `auth.json`. To pool accounts, put them in
|
|
121
|
+
a CLAI2 fallback chain, `/chain NAME MODEL MODEL...`, then `/model chain:NAME`.
|
|
122
|
+
Older CLAI2 builds ignore profiles.
|
|
123
|
+
|
|
113
124
|
### Settings menu
|
|
114
125
|
|
|
115
126
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -121,7 +132,8 @@ opens it. Every change is saved right away and applies from the next run.
|
|
|
121
132
|
| Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
|
|
122
133
|
|
|
123
134
|
`/claude_code logout` and `/claude_code status` do the
|
|
124
|
-
same without the menu
|
|
135
|
+
same without the menu; add a profile name (`/claude_code logout work`) for
|
|
136
|
+
another account.
|
|
125
137
|
|
|
126
138
|
### Where the sign-in lives
|
|
127
139
|
|
|
@@ -140,7 +152,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
|
|
|
140
152
|
after switching.
|
|
141
153
|
|
|
142
154
|
If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
|
|
143
|
-
expired`, run `/login claude`. If the
|
|
155
|
+
expired`, run `/login claude-code`. If the
|
|
144
156
|
plugin fails to load with `cannot import name 'Plugin' from
|
|
145
157
|
'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
|
|
146
158
|
[Install](#install), or pin plugin 0.5.0.
|
|
@@ -153,6 +165,11 @@ provider. Instead of a `claude-code:` model string, construct
|
|
|
153
165
|
`ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
|
|
154
166
|
`ClaudeCodeProvider` by default.
|
|
155
167
|
|
|
168
|
+
`ClaudeCodeModel` enables prompt caching with a **1-hour TTL** by default. Override it with
|
|
169
|
+
`settings=AnthropicModelSettings(anthropic_cache="5m")`, or disable default caching with
|
|
170
|
+
`settings=AnthropicModelSettings(anthropic_cache=False)`. Per-request settings take precedence.
|
|
171
|
+
Tool-definition, static-instruction, and latest-tool-call breakpoints use Pydantic AI's caching implementation.
|
|
172
|
+
|
|
156
173
|
### Quick start
|
|
157
174
|
|
|
158
175
|
```python
|
|
@@ -283,7 +300,7 @@ uv run pytest
|
|
|
283
300
|
|
|
284
301
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
285
302
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
286
|
-
push a matching tag (`git tag v0.
|
|
303
|
+
push a matching tag (`git tag v0.7.0 && git push origin v0.7.0`). The `Publish` workflow tests,
|
|
287
304
|
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
288
305
|
|
|
289
306
|
The tests never touch your real keychain or token file. They run against a
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/bin/sh
|
|
2
|
-
# Install or update the Claude Code plugin for CLAI2, at the latest release (pass a tag such as v0.
|
|
2
|
+
# Install or update the Claude Code plugin for CLAI2, at the latest release (pass a tag such as v0.7.0, or main):
|
|
3
3
|
# curl -fsSL https://raw.githubusercontent.com/mpfaffenberger/pydantic-ai-claude-code/main/install.sh | sh
|
|
4
4
|
set -eu
|
|
5
5
|
|
|
@@ -7,7 +7,7 @@ ref="${1:-}"
|
|
|
7
7
|
if [ -z "$ref" ]; then
|
|
8
8
|
version=$(curl -fsSL https://pypi.org/pypi/pydantic-claude-code/json | grep -o '"version": *"[^"]*"' | head -n 1 | cut -d '"' -f 4)
|
|
9
9
|
if [ -z "$version" ]; then
|
|
10
|
-
echo "Could not look up the latest release on PyPI. Pass a tag (sh -s -- v0.
|
|
10
|
+
echo "Could not look up the latest release on PyPI. Pass a tag (sh -s -- v0.7.0) or main." >&2
|
|
11
11
|
exit 1
|
|
12
12
|
fi
|
|
13
13
|
ref="v$version"
|
|
@@ -24,4 +24,4 @@ rm -rf "$target"
|
|
|
24
24
|
mv "$download"/*/src/pydantic_ai_claude_code "$target"
|
|
25
25
|
|
|
26
26
|
echo "Installed the Claude Code plugin ($ref) to $target."
|
|
27
|
-
echo "Start clai2, sign in with /login claude, then /model claude-code:claude-opus-5-5."
|
|
27
|
+
echo "Start clai2, sign in with /login claude-code, then /model claude-code:claude-opus-5-5."
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "pydantic-claude-code"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
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"
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__init__.py
RENAMED
|
@@ -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.
|
|
29
|
+
__version__ = "0.7.0"
|
|
30
30
|
"""Matches `version` in pyproject.toml (a test checks), so a copied folder knows its release."""
|
|
31
31
|
|
|
32
32
|
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/auth.py
RENAMED
|
@@ -32,7 +32,7 @@ class ClaudeCodeSignInExpiredError(UserError):
|
|
|
32
32
|
"""`reason` is why the refresh failed, as the token endpoint put it."""
|
|
33
33
|
super().__init__(
|
|
34
34
|
f"Your Claude Code sign-in has expired or was revoked; sign in again. ({reason}) "
|
|
35
|
-
"In CLAI2 run /login claude; from Python, `await pydantic_ai_claude_code.login()` "
|
|
35
|
+
"In CLAI2 run /login claude-code; from Python, `await pydantic_ai_claude_code.login()` "
|
|
36
36
|
"or `python -m pydantic_ai_claude_code login`."
|
|
37
37
|
)
|
|
38
38
|
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/clai2.py
RENAMED
|
@@ -2,21 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
Install it by copying this package's folder into CLAI2's plugins folder as `claude_code/`; CLAI2 loads it at
|
|
4
4
|
startup through the `ClaudeCodePlugin` the package's `__init__.py` declares. Everything it imports already ships with CLAI2, and it uses only
|
|
5
|
-
relative imports, so the copy runs on its own. `/login claude` signs in through the browser, and `/claude_code`
|
|
5
|
+
relative imports, so the copy runs on its own. `/login claude-code` signs in through the browser, and `/claude_code`
|
|
6
6
|
(or `C` in `/plugins`) opens the settings menu: sign in, sign out, and choose where the sign-in is kept. Then
|
|
7
7
|
pick a model in `/add_model` > `claude-code`.
|
|
8
8
|
|
|
9
9
|
The sign-in is an OAuth token pair, not an API key, so it does not go in `/keys`. It is kept where this
|
|
10
10
|
package keeps it outside CLAI2 (the OS keyring by default), so one sign-in serves CLAI2 and your own agents.
|
|
11
11
|
Plugin settings, which are plaintext SQLite, hold only the storage choice.
|
|
12
|
+
|
|
13
|
+
On a CLAI2 build with auth profiles, `/login claude-code@PROFILE` signs in another account, kept apart from the
|
|
14
|
+
default one, and `claude-code@PROFILE:MODEL` runs on it. A CLAI2 fallback chain can pool those accounts.
|
|
12
15
|
"""
|
|
13
16
|
|
|
14
17
|
from __future__ import annotations
|
|
15
18
|
|
|
16
19
|
import asyncio
|
|
20
|
+
import dataclasses
|
|
17
21
|
import sys
|
|
18
22
|
from collections.abc import Callable, Sequence
|
|
19
|
-
from typing import IO, get_args
|
|
23
|
+
from typing import IO, Any, get_args
|
|
20
24
|
|
|
21
25
|
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
22
26
|
from pydantic_ai.exceptions import UserError
|
|
@@ -38,12 +42,30 @@ PREFIX = "claude-code"
|
|
|
38
42
|
COMMAND = "claude_code"
|
|
39
43
|
"""CLAI2 command names are Python identifiers, so the command cannot share the prefix's hyphen."""
|
|
40
44
|
|
|
41
|
-
LOGIN =
|
|
42
|
-
"""`/login claude` signs in."""
|
|
45
|
+
LOGIN = PREFIX
|
|
46
|
+
"""`/login claude-code` signs in, matching the `claude-code:` models it unlocks."""
|
|
43
47
|
|
|
44
48
|
SIGNED_IN = "signed in"
|
|
45
49
|
SIGNED_OUT = "not signed in"
|
|
46
|
-
_HELP =
|
|
50
|
+
_HELP = (
|
|
51
|
+
f"Usage: /{COMMAND} (settings menu), /{COMMAND} logout [PROFILE], or /{COMMAND} status [PROFILE]. "
|
|
52
|
+
f"Sign in with /login {LOGIN}."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _login(profile: str | None) -> str:
|
|
57
|
+
"""The `/login` argument for a profile: `claude-code`, or `claude-code@PROFILE`."""
|
|
58
|
+
return LOGIN if profile is None else f"{LOGIN}@{profile}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _account(profile: str | None) -> str:
|
|
62
|
+
return "Claude Code" if profile is None else f"Claude Code profile {profile}"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _supported(cls: type, **optional: Any) -> dict[str, Any]:
|
|
66
|
+
"""The keyword arguments `cls` accepts: CLAI2 builds without auth profiles lack those fields."""
|
|
67
|
+
names = {field.name for field in dataclasses.fields(cls)}
|
|
68
|
+
return {key: value for key, value in optional.items() if key in names}
|
|
47
69
|
|
|
48
70
|
|
|
49
71
|
class ClaudeCodeSettings(BaseModel):
|
|
@@ -57,9 +79,9 @@ class ClaudeCodeSettings(BaseModel):
|
|
|
57
79
|
)
|
|
58
80
|
|
|
59
81
|
|
|
60
|
-
def token_store(backend: Backend) -> TokenStore:
|
|
61
|
-
"""The store for a plugin setting; `auto` defers to `CLAUDE_CODE_CREDENTIALS`, as the package does."""
|
|
62
|
-
return default_store(None if backend == "auto" else backend)
|
|
82
|
+
def token_store(backend: Backend, profile: str | None = None) -> TokenStore:
|
|
83
|
+
"""The store for a plugin setting and profile; `auto` defers to `CLAUDE_CODE_CREDENTIALS`, as the package does."""
|
|
84
|
+
return default_store(None if backend == "auto" else backend, profile)
|
|
63
85
|
|
|
64
86
|
|
|
65
87
|
class ClaudeCodeConfig:
|
|
@@ -76,9 +98,9 @@ class ClaudeCodeConfig:
|
|
|
76
98
|
self.settings = settings
|
|
77
99
|
self._save = save
|
|
78
100
|
|
|
79
|
-
def store(self) -> TokenStore:
|
|
80
|
-
"""The token store the current settings choose."""
|
|
81
|
-
return token_store(self.settings.credentials)
|
|
101
|
+
def store(self, profile: str | None = None) -> TokenStore:
|
|
102
|
+
"""The token store the current settings choose, for the default account or a profile."""
|
|
103
|
+
return token_store(self.settings.credentials, profile)
|
|
82
104
|
|
|
83
105
|
def rows(self) -> Sequence[FieldRow]:
|
|
84
106
|
"""The sign-in first, then where it is kept."""
|
|
@@ -134,7 +156,7 @@ class ClaudeCodeConfig:
|
|
|
134
156
|
|
|
135
157
|
|
|
136
158
|
class Providers:
|
|
137
|
-
"""One provider per store, reused across runs so they share a connection pool.
|
|
159
|
+
"""One provider per store and profile, reused across runs so they share a connection pool.
|
|
138
160
|
|
|
139
161
|
A provider is rebuilt when the stored sign-in differs from the one it holds: after signing in again here
|
|
140
162
|
or from another process. Refreshes the provider makes itself are saved back, so they keep it in step.
|
|
@@ -142,34 +164,38 @@ class Providers:
|
|
|
142
164
|
|
|
143
165
|
def __init__(self) -> None:
|
|
144
166
|
"""Start empty; a provider is built on the first run."""
|
|
145
|
-
self._cached: dict[Backend, ClaudeCodeProvider] = {}
|
|
167
|
+
self._cached: dict[tuple[Backend, str | None], ClaudeCodeProvider] = {}
|
|
146
168
|
|
|
147
|
-
def model(self, name: str, source: ClaudeCodeConfig) -> ClaudeCodeModel:
|
|
169
|
+
def model(self, name: str, source: ClaudeCodeConfig, profile: str | None = None) -> ClaudeCodeModel:
|
|
148
170
|
"""Build `name` on the stored sign-in, raising `UserError` with setup steps when there is none."""
|
|
149
|
-
|
|
150
|
-
store =
|
|
171
|
+
key = (source.settings.credentials, profile)
|
|
172
|
+
store = source.store(profile)
|
|
151
173
|
credentials = store.load()
|
|
152
174
|
if credentials is None:
|
|
153
|
-
raise UserError(f"Sign in to Claude Code first: /login {
|
|
154
|
-
provider = self._cached.get(
|
|
175
|
+
raise UserError(f"Sign in to Claude Code first: /login {_login(profile)}.")
|
|
176
|
+
provider = self._cached.get(key)
|
|
155
177
|
if provider is None or provider.credentials != credentials:
|
|
156
|
-
provider = self._cached[
|
|
178
|
+
provider = self._cached[key] = ClaudeCodeProvider(credentials, store=store)
|
|
157
179
|
return ClaudeCodeModel(name, provider=provider)
|
|
158
180
|
|
|
159
181
|
|
|
160
|
-
def status(source: ClaudeCodeConfig) -> str:
|
|
182
|
+
def status(source: ClaudeCodeConfig, profile: str | None = None) -> str:
|
|
161
183
|
"""One line on whether the plugin can run models, and where the sign-in lives."""
|
|
162
|
-
store = source.store()
|
|
184
|
+
store = source.store(profile)
|
|
163
185
|
where = f"the file {store.path}" if isinstance(store, ClaudeCodeTokenStore) else "the OS keyring"
|
|
164
186
|
if store.load() is None:
|
|
165
|
-
|
|
166
|
-
|
|
187
|
+
to = "" if profile is None else f" to profile {profile}"
|
|
188
|
+
return f"Not signed in{to} (sign-in would be kept in {where}). Run /login {_login(profile)}."
|
|
189
|
+
return f"Signed in to {_account(profile)}; tokens are kept in {where}."
|
|
167
190
|
|
|
168
191
|
|
|
169
|
-
async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None]) -> str:
|
|
192
|
+
async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None], profile: str | None = None) -> str:
|
|
170
193
|
"""Sign in through the browser, or a pasted redirect address, and save the tokens to the chosen store."""
|
|
171
|
-
|
|
194
|
+
store = source.store(profile)
|
|
195
|
+
await login(store=store, on_url=show_url, read_pasteback=lambda: run_worker(read_pasted_url))
|
|
172
196
|
first = config.MODELS[0]
|
|
197
|
+
if profile is not None:
|
|
198
|
+
return f"Signed in to {_account(profile)}. Run /model {PREFIX}@{profile}:{first}, or any other model."
|
|
173
199
|
return f"Signed in to Claude Code. Choose a model in /add_model > {PREFIX}, or run /model {PREFIX}:{first}."
|
|
174
200
|
|
|
175
201
|
|
|
@@ -216,10 +242,10 @@ def read_pasted_url(keys: Callable[[], str] = menu_key, output: IO[str] = sys.st
|
|
|
216
242
|
draw()
|
|
217
243
|
|
|
218
244
|
|
|
219
|
-
def sign_out(source: ClaudeCodeConfig) -> str:
|
|
245
|
+
def sign_out(source: ClaudeCodeConfig, profile: str | None = None) -> str:
|
|
220
246
|
"""Forget the stored tokens; runs with `claude-code:` models then ask to sign in again."""
|
|
221
|
-
source.store().delete()
|
|
222
|
-
return "Signed out of
|
|
247
|
+
source.store(profile).delete()
|
|
248
|
+
return f"Signed out of {_account(profile)}. The tokens stay valid at Anthropic until they expire."
|
|
223
249
|
|
|
224
250
|
|
|
225
251
|
async def configure(source: ClaudeCodeConfig, show_url: Callable[[str], None], runners: Runners = TERMINAL) -> str:
|
|
@@ -236,7 +262,7 @@ async def configure(source: ClaudeCodeConfig, show_url: Callable[[str], None], r
|
|
|
236
262
|
|
|
237
263
|
|
|
238
264
|
class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
239
|
-
"""`claude-code:` models, `/login claude`, the settings menu, `/claude_code`, and the update notice."""
|
|
265
|
+
"""`claude-code:` models, `/login claude-code`, the settings menu, `/claude_code`, and the update notice."""
|
|
240
266
|
|
|
241
267
|
def __init__(self, host: PluginHost, settings: ClaudeCodeSettings) -> None:
|
|
242
268
|
"""Build the provider and the menu's source once; CLAI2 loads the plugin again when settings change."""
|
|
@@ -245,12 +271,19 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
245
271
|
self._providers = Providers()
|
|
246
272
|
self._update: asyncio.Task[str | None] | None = None
|
|
247
273
|
self.provider = ModelProvider(
|
|
248
|
-
prefix=PREFIX,
|
|
274
|
+
prefix=PREFIX,
|
|
275
|
+
resolve=self._resolve,
|
|
276
|
+
models=config.MODELS,
|
|
277
|
+
settings_from="anthropic",
|
|
278
|
+
**_supported(ModelProvider, resolve_profile=self._resolve_profile),
|
|
249
279
|
)
|
|
250
280
|
|
|
251
281
|
def _resolve(self, name: str) -> ClaudeCodeModel:
|
|
252
282
|
return self._providers.model(name, self.source)
|
|
253
283
|
|
|
284
|
+
def _resolve_profile(self, name: str, profile: str) -> ClaudeCodeModel:
|
|
285
|
+
return self._providers.model(name, self.source, profile)
|
|
286
|
+
|
|
254
287
|
def _show_url(self, url: str) -> None:
|
|
255
288
|
self.host.console.print(
|
|
256
289
|
"Opening your browser to sign in to Claude Code. If it does not open, or this machine's browser "
|
|
@@ -263,11 +296,21 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
263
296
|
return (self.provider,)
|
|
264
297
|
|
|
265
298
|
def get_logins(self) -> Sequence[PluginLogin]:
|
|
266
|
-
return (
|
|
299
|
+
return (
|
|
300
|
+
PluginLogin(
|
|
301
|
+
name=LOGIN,
|
|
302
|
+
handler=self._sign_in,
|
|
303
|
+
models=self.provider.names,
|
|
304
|
+
**_supported(PluginLogin, profile_handler=self._sign_in_profile),
|
|
305
|
+
),
|
|
306
|
+
)
|
|
267
307
|
|
|
268
308
|
async def _sign_in(self) -> str:
|
|
269
309
|
return await sign_in(self.source, self._show_url)
|
|
270
310
|
|
|
311
|
+
async def _sign_in_profile(self, profile: str) -> str:
|
|
312
|
+
return await sign_in(self.source, self._show_url, profile)
|
|
313
|
+
|
|
271
314
|
def get_commands(self) -> Sequence[Command]:
|
|
272
315
|
return (
|
|
273
316
|
Command(
|
|
@@ -286,11 +329,10 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
286
329
|
async def _command(self, args: list[str]) -> str:
|
|
287
330
|
if not args:
|
|
288
331
|
return await self.configure()
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
raise ValueError(_HELP)
|
|
332
|
+
action = {"logout": sign_out, "status": status}.get(args[0])
|
|
333
|
+
if action is None or len(args) > 2:
|
|
334
|
+
raise ValueError(_HELP)
|
|
335
|
+
return await asyncio.to_thread(action, self.source, args[1] if len(args) == 2 else None)
|
|
294
336
|
|
|
295
337
|
async def configure(self) -> str:
|
|
296
338
|
return await configure(self.source, self._show_url)
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/model.py
RENAMED
|
@@ -10,7 +10,7 @@ from pydantic_ai import RunContext
|
|
|
10
10
|
from pydantic_ai.exceptions import ModelAPIError
|
|
11
11
|
from pydantic_ai.messages import ModelMessage, ModelRequest, ModelResponse, SystemPromptPart
|
|
12
12
|
from pydantic_ai.models import ModelRequestParameters, StreamedResponse
|
|
13
|
-
from pydantic_ai.models.anthropic import AnthropicModel
|
|
13
|
+
from pydantic_ai.models.anthropic import AnthropicModel, AnthropicModelSettings
|
|
14
14
|
from pydantic_ai.providers import Provider
|
|
15
15
|
from pydantic_ai.settings import ModelSettings
|
|
16
16
|
|
|
@@ -32,6 +32,7 @@ class ClaudeCodeModel(AnthropicModel):
|
|
|
32
32
|
model_name: str,
|
|
33
33
|
*,
|
|
34
34
|
provider: Provider[Any] | None = None,
|
|
35
|
+
settings: ModelSettings | None = None,
|
|
35
36
|
**kwargs: Any,
|
|
36
37
|
) -> None:
|
|
37
38
|
"""Initialize a Claude Code model.
|
|
@@ -45,7 +46,10 @@ class ClaudeCodeModel(AnthropicModel):
|
|
|
45
46
|
from .provider import ClaudeCodeProvider
|
|
46
47
|
|
|
47
48
|
provider = ClaudeCodeProvider()
|
|
48
|
-
|
|
49
|
+
defaults = AnthropicModelSettings(
|
|
50
|
+
anthropic_cache=False if settings and settings.get("anthropic_cache_messages") else "1h",
|
|
51
|
+
)
|
|
52
|
+
super().__init__(model_name, provider=provider, settings={**defaults, **(settings or {})}, **kwargs)
|
|
49
53
|
|
|
50
54
|
def prepare_messages(
|
|
51
55
|
self,
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/storage.py
RENAMED
|
@@ -5,12 +5,16 @@ Manager on Windows, Secret Service on Linux. When no keychain is available, a
|
|
|
5
5
|
JSON file readable only by you (`0600`) is used instead. Force a backend with the
|
|
6
6
|
`CLAUDE_CODE_CREDENTIALS` env var (`keyring` or `file`), or pass it to `default_store`;
|
|
7
7
|
the file path honors `CLAUDE_CODE_AUTH_FILE`.
|
|
8
|
+
|
|
9
|
+
A named profile keeps a second account apart: keyring user name `PROFILE`, or the
|
|
10
|
+
file `auth-PROFILE.json` next to the default one. No profile is the default account.
|
|
8
11
|
"""
|
|
9
12
|
|
|
10
13
|
from __future__ import annotations
|
|
11
14
|
|
|
12
15
|
import json
|
|
13
16
|
import os
|
|
17
|
+
import re
|
|
14
18
|
from pathlib import Path
|
|
15
19
|
from typing import Literal, Protocol, get_args
|
|
16
20
|
|
|
@@ -19,6 +23,7 @@ from pydantic_ai.exceptions import UserError
|
|
|
19
23
|
from .credentials import ClaudeCodeCredentials
|
|
20
24
|
|
|
21
25
|
_FILE_PERMISSIONS = 0o600
|
|
26
|
+
_PROFILE = re.compile(r"[a-z0-9][a-z0-9_-]{0,31}")
|
|
22
27
|
|
|
23
28
|
Backend = Literal["auto", "keyring", "file"]
|
|
24
29
|
"""Where credentials live: `auto` uses the keyring when one exists, else the file."""
|
|
@@ -40,24 +45,34 @@ class TokenStore(Protocol):
|
|
|
40
45
|
...
|
|
41
46
|
|
|
42
47
|
|
|
43
|
-
def
|
|
44
|
-
"""
|
|
48
|
+
def check_profile(profile: str) -> str:
|
|
49
|
+
"""Return `profile` if it is a valid profile name, else raise `UserError`."""
|
|
50
|
+
if not _PROFILE.fullmatch(profile) or profile == KeyringTokenStore.USERNAME:
|
|
51
|
+
raise UserError(
|
|
52
|
+
f"Profile {profile!r} must be 1 to 32 lowercase letters, digits, hyphens, or underscores, starting with "
|
|
53
|
+
"a letter or digit, and not 'default' (the account without a profile)."
|
|
54
|
+
)
|
|
55
|
+
return profile
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def default_auth_path(profile: str | None = None) -> Path:
|
|
59
|
+
"""The fallback token file path, honoring `CLAUDE_CODE_AUTH_FILE`; a profile's file sits next to it."""
|
|
45
60
|
env_path = os.environ.get("CLAUDE_CODE_AUTH_FILE")
|
|
46
61
|
if env_path:
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
62
|
+
path = Path(env_path).expanduser()
|
|
63
|
+
else:
|
|
64
|
+
data_dir = Path(os.environ.get("XDG_DATA_HOME", "") or (Path.home() / ".local" / "share"))
|
|
65
|
+
path = data_dir / "pydantic-ai-claude-code" / "auth.json"
|
|
66
|
+
return path if profile is None else path.with_name(f"auth-{check_profile(profile)}.json")
|
|
50
67
|
|
|
51
68
|
|
|
52
|
-
def default_store(backend: Backend | None = None) -> TokenStore:
|
|
53
|
-
"""The store for `backend
|
|
69
|
+
def default_store(backend: Backend | None = None, profile: str | None = None) -> TokenStore:
|
|
70
|
+
"""The store for `backend` and `profile`; `backend` defaults to `CLAUDE_CODE_CREDENTIALS`, then `auto`."""
|
|
54
71
|
if backend is None:
|
|
55
72
|
backend = _env_backend()
|
|
56
|
-
if backend == "file":
|
|
57
|
-
return ClaudeCodeTokenStore()
|
|
58
|
-
if
|
|
59
|
-
return KeyringTokenStore()
|
|
60
|
-
return ClaudeCodeTokenStore()
|
|
73
|
+
if backend == "file" or (backend == "auto" and not _keyring_available()):
|
|
74
|
+
return ClaudeCodeTokenStore(default_auth_path(profile))
|
|
75
|
+
return KeyringTokenStore(username=KeyringTokenStore.USERNAME if profile is None else check_profile(profile))
|
|
61
76
|
|
|
62
77
|
|
|
63
78
|
def _env_backend() -> Backend:
|
|
@@ -103,7 +118,7 @@ class KeyringTokenStore:
|
|
|
103
118
|
"""OS-keyring store backed by the `keyring` package.
|
|
104
119
|
|
|
105
120
|
The service name is `pydantic-ai-claude-code` and credentials are stored as
|
|
106
|
-
a single JSON blob under the `default` user name.
|
|
121
|
+
a single JSON blob under the `default` user name, or the profile's name.
|
|
107
122
|
"""
|
|
108
123
|
|
|
109
124
|
SERVICE = "pydantic-ai-claude-code"
|
|
@@ -9,6 +9,7 @@ import shutil
|
|
|
9
9
|
import subprocess
|
|
10
10
|
import sys
|
|
11
11
|
from collections.abc import Awaitable, Callable
|
|
12
|
+
from dataclasses import dataclass
|
|
12
13
|
from pathlib import Path
|
|
13
14
|
from typing import Generic, TypeVar, cast
|
|
14
15
|
|
|
@@ -16,11 +17,21 @@ import pytest
|
|
|
16
17
|
from pydantic import JsonValue
|
|
17
18
|
from pydantic_ai import Agent
|
|
18
19
|
from pydantic_ai.exceptions import UserError
|
|
20
|
+
from pydantic_ai.models import Model
|
|
19
21
|
from pydantic_clai2 import chat
|
|
20
22
|
from pydantic_clai2.commands import Command
|
|
21
23
|
from pydantic_clai2.config import Settings
|
|
22
24
|
from pydantic_clai2.config.settings_store import SettingsStore
|
|
23
|
-
from pydantic_clai2.plugins import
|
|
25
|
+
from pydantic_clai2.plugins import (
|
|
26
|
+
LoadedPlugin,
|
|
27
|
+
ModelProvider,
|
|
28
|
+
PluginHost,
|
|
29
|
+
PluginLogin,
|
|
30
|
+
SessionEnd,
|
|
31
|
+
SessionStart,
|
|
32
|
+
TurnEnd,
|
|
33
|
+
load_plugin,
|
|
34
|
+
)
|
|
24
35
|
from pydantic_clai2.ui.menus.field_menu import Runners
|
|
25
36
|
from rich.console import Console
|
|
26
37
|
from termflow.tui import MenuItem
|
|
@@ -41,7 +52,7 @@ from pydantic_ai_claude_code.clai2 import (
|
|
|
41
52
|
)
|
|
42
53
|
from pydantic_ai_claude_code.credentials import ClaudeCodeCredentials
|
|
43
54
|
from pydantic_ai_claude_code.model import ClaudeCodeModel
|
|
44
|
-
from pydantic_ai_claude_code.storage import ClaudeCodeTokenStore, KeyringTokenStore, TokenStore
|
|
55
|
+
from pydantic_ai_claude_code.storage import ClaudeCodeTokenStore, KeyringTokenStore, TokenStore, default_auth_path
|
|
45
56
|
|
|
46
57
|
PromptT = TypeVar("PromptT")
|
|
47
58
|
CREDS = ClaudeCodeCredentials(access_token="sub-token", refresh_token="refresh")
|
|
@@ -110,7 +121,7 @@ def test_the_plugin_declares_the_prefix_the_login_the_menu_and_the_command() ->
|
|
|
110
121
|
assert provider.names == tuple(f"claude-code:{name}" for name in config.MODELS)
|
|
111
122
|
assert provider.settings_from == "anthropic"
|
|
112
123
|
[login] = loaded.logins
|
|
113
|
-
assert login.name == "claude"
|
|
124
|
+
assert login.name == "claude-code"
|
|
114
125
|
assert login.models == provider.names, "signing in adds every listed model"
|
|
115
126
|
assert loaded.plugin.has_configure
|
|
116
127
|
assert list(command(loaded).complete(["lo"])) == ["logout"]
|
|
@@ -133,7 +144,7 @@ def test_the_package_imports_without_clai2() -> None:
|
|
|
133
144
|
|
|
134
145
|
def test_resolve_needs_a_sign_in_and_reuses_the_provider_until_it_changes() -> None:
|
|
135
146
|
[provider] = load().model_providers
|
|
136
|
-
with pytest.raises(UserError, match="Sign in to Claude Code first: /login claude"):
|
|
147
|
+
with pytest.raises(UserError, match="Sign in to Claude Code first: /login claude-code"):
|
|
137
148
|
provider.resolve("claude-opus-5-5")
|
|
138
149
|
|
|
139
150
|
store = ClaudeCodeTokenStore() # `auto` without a keychain, as in these tests, is the file
|
|
@@ -167,7 +178,7 @@ async def test_login_claude_then_the_command_reports_and_signs_out(
|
|
|
167
178
|
assert (await run(loaded, "logout")).startswith("Signed out of Claude Code.")
|
|
168
179
|
assert ClaudeCodeTokenStore().load() is None
|
|
169
180
|
for retired in ("login", "bogus"):
|
|
170
|
-
with pytest.raises(ValueError, match="Usage: /claude_code .*Sign in with /login claude"):
|
|
181
|
+
with pytest.raises(ValueError, match="Usage: /claude_code .*Sign in with /login claude-code"):
|
|
171
182
|
await run(loaded, retired)
|
|
172
183
|
|
|
173
184
|
|
|
@@ -247,7 +258,7 @@ async def test_menu_switches_storage_then_signs_in(monkeypatch: pytest.MonkeyPat
|
|
|
247
258
|
assert saved == [ClaudeCodeSettings(credentials="file")]
|
|
248
259
|
assert message.splitlines() == [
|
|
249
260
|
"Claude Code credential storage: File (0600). "
|
|
250
|
-
f"Not signed in (sign-in would be kept in the file {ClaudeCodeTokenStore().path}). Run /login claude.",
|
|
261
|
+
f"Not signed in (sign-in would be kept in the file {ClaudeCodeTokenStore().path}). Run /login claude-code.",
|
|
251
262
|
"Signed in to Claude Code. Choose a model in /add_model > claude-code, or run /model claude-code:claude-opus-5-5.",
|
|
252
263
|
]
|
|
253
264
|
assert urls == [URL]
|
|
@@ -342,7 +353,7 @@ async def test_clai2_runs_the_package_folder_as_a_drop_in(
|
|
|
342
353
|
)
|
|
343
354
|
|
|
344
355
|
assert f"claude_code: {drop_in / '__init__.py'} (enabled, loaded)" in shown.getvalue()
|
|
345
|
-
assert "Usage: /login [codex|copilot|claude]" in shown.getvalue()
|
|
356
|
+
assert "Usage: /login [codex|copilot|claude-code]" in shown.getvalue()
|
|
346
357
|
assert TEXT in shown.getvalue()
|
|
347
358
|
assert messages_stub.received["model"] == "claude-opus-5-5"
|
|
348
359
|
loaded = {
|
|
@@ -394,3 +405,63 @@ async def test_sign_in_offers_the_paste_reader_to_login(monkeypatch: pytest.Monk
|
|
|
394
405
|
source = ClaudeCodeConfig(ClaudeCodeSettings(), lambda settings: None)
|
|
395
406
|
assert (await clai2.sign_in(source, print)).startswith("Signed in to Claude Code.")
|
|
396
407
|
assert offered == [PASTED]
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
@dataclass(frozen=True, kw_only=True)
|
|
411
|
+
class ProfileProvider(ModelProvider):
|
|
412
|
+
"""`ModelProvider` as a CLAI2 build with auth profiles declares it."""
|
|
413
|
+
|
|
414
|
+
resolve_profile: Callable[[str, str], Model] | None = None
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
@dataclass(frozen=True, kw_only=True)
|
|
418
|
+
class ProfileLogin(PluginLogin):
|
|
419
|
+
"""`PluginLogin` as a CLAI2 build with auth profiles declares it."""
|
|
420
|
+
|
|
421
|
+
profile_handler: Callable[[str], Awaitable[str]] | None = None
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def test_older_clai2_builds_are_not_offered_profiles() -> None:
|
|
425
|
+
@dataclass
|
|
426
|
+
class Older:
|
|
427
|
+
prefix: str
|
|
428
|
+
|
|
429
|
+
assert clai2._supported(Older, resolve_profile=print) == {}
|
|
430
|
+
assert clai2._supported(ProfileProvider, resolve_profile=print) == {"resolve_profile": print}
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
async def test_each_profile_signs_in_and_runs_on_its_own_tokens(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
434
|
+
monkeypatch.setattr(clai2, "ModelProvider", ProfileProvider)
|
|
435
|
+
monkeypatch.setattr(clai2, "PluginLogin", ProfileLogin)
|
|
436
|
+
monkeypatch.setattr(clai2, "login", fake_login)
|
|
437
|
+
loaded = load()
|
|
438
|
+
[provider] = loaded.model_providers
|
|
439
|
+
[login] = loaded.logins
|
|
440
|
+
assert isinstance(provider, ProfileProvider) and provider.resolve_profile is not None
|
|
441
|
+
assert isinstance(login, ProfileLogin) and login.profile_handler is not None
|
|
442
|
+
with pytest.raises(UserError, match="Sign in to Claude Code first: /login claude-code@work."):
|
|
443
|
+
provider.resolve_profile("claude-opus-5-5", "work")
|
|
444
|
+
|
|
445
|
+
assert await login.profile_handler("work") == (
|
|
446
|
+
"Signed in to Claude Code profile work. Run /model claude-code@work:claude-opus-5-5, or any other model."
|
|
447
|
+
)
|
|
448
|
+
assert ClaudeCodeTokenStore(default_auth_path("work")).load() == CREDS
|
|
449
|
+
with pytest.raises(UserError, match="/login claude-code.$"):
|
|
450
|
+
provider.resolve("claude-opus-5-5") # the default account is still signed out
|
|
451
|
+
|
|
452
|
+
ClaudeCodeTokenStore().save(ClaudeCodeCredentials(access_token="default", refresh_token="r"))
|
|
453
|
+
work = provider.resolve_profile("claude-opus-5-5", "work")
|
|
454
|
+
default = provider.resolve("claude-opus-5-5")
|
|
455
|
+
assert isinstance(work, ClaudeCodeModel) and isinstance(default, ClaudeCodeModel)
|
|
456
|
+
assert work.client is not default.client, "two accounts never share a provider"
|
|
457
|
+
again = provider.resolve_profile("claude-sonnet-5-5", "work")
|
|
458
|
+
assert isinstance(again, ClaudeCodeModel) and again.client is work.client
|
|
459
|
+
|
|
460
|
+
assert (await run(loaded, "status", "work")).startswith("Signed in to Claude Code profile work; tokens")
|
|
461
|
+
assert (await run(loaded, "logout", "work")).startswith("Signed out of Claude Code profile work.")
|
|
462
|
+
assert (await run(loaded, "status", "work")).startswith("Not signed in to profile work (")
|
|
463
|
+
assert (await run(loaded, "status")).startswith("Signed in to Claude Code; tokens")
|
|
464
|
+
with pytest.raises(UserError, match="must be 1 to 32 lowercase"):
|
|
465
|
+
await run(loaded, "status", "Work")
|
|
466
|
+
with pytest.raises(ValueError, match="Usage: /claude_code"):
|
|
467
|
+
await run(loaded, "status", "work", "extra")
|
|
@@ -76,5 +76,5 @@ def test_says_what_to_do_when_pypi_has_no_answer(fake_curl: Path) -> None:
|
|
|
76
76
|
(fake_curl / "releases.json").write_text("")
|
|
77
77
|
done = install(fake_curl, check=False)
|
|
78
78
|
assert done.returncode == 1
|
|
79
|
-
assert "Pass a tag (sh -s -- v0.
|
|
79
|
+
assert "Pass a tag (sh -s -- v0.7.0) or main." in done.stderr
|
|
80
80
|
assert not (fake_curl / "pydantic-clai2").exists()
|
|
@@ -106,3 +106,17 @@ def test_default_store_bad_env_raises(monkeypatch) -> None:
|
|
|
106
106
|
monkeypatch.setenv("CLAUDE_CODE_CREDENTIALS", "bogus")
|
|
107
107
|
with pytest.raises(UserError):
|
|
108
108
|
default_store()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_a_profile_has_its_own_keyring_entry_and_no_profile_keeps_the_default(fake_keyring) -> None:
|
|
112
|
+
default_store("keyring").save(ClaudeCodeCredentials(access_token="a", refresh_token="b"))
|
|
113
|
+
default_store("keyring", "work").save(ClaudeCodeCredentials(access_token="w", refresh_token="x"))
|
|
114
|
+
assert set(fake_keyring) == {(KeyringTokenStore.SERVICE, "default"), (KeyringTokenStore.SERVICE, "work")}
|
|
115
|
+
assert default_store("keyring").load() == ClaudeCodeCredentials(access_token="a", refresh_token="b")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@pytest.mark.parametrize("profile", ["Work", "-x", "a b", "x" * 33, "", "default"])
|
|
119
|
+
def test_bad_profile_names_are_refused(profile: str) -> None:
|
|
120
|
+
for backend in ("keyring", "file"):
|
|
121
|
+
with pytest.raises(UserError, match="must be 1 to 32 lowercase"):
|
|
122
|
+
default_store(backend, profile)
|
|
@@ -0,0 +1,59 @@
|
|
|
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
|
+
)
|
|
@@ -58,3 +58,11 @@ def test_default_path_uses_data_dir(monkeypatch, tmp_path) -> None:
|
|
|
58
58
|
monkeypatch.delenv("CLAUDE_CODE_AUTH_FILE", raising=False)
|
|
59
59
|
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
|
|
60
60
|
assert default_auth_path() == tmp_path / "pydantic-ai-claude-code" / "auth.json"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_a_profile_file_sits_next_to_the_default_one(monkeypatch, tmp_path) -> None:
|
|
64
|
+
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
|
|
65
|
+
assert default_auth_path("work_2") == tmp_path / "pydantic-ai-claude-code" / "auth-work_2.json"
|
|
66
|
+
monkeypatch.setenv("CLAUDE_CODE_AUTH_FILE", str(tmp_path / "custom.json"))
|
|
67
|
+
assert default_auth_path("work") == tmp_path / "auth-work.json"
|
|
68
|
+
assert default_auth_path() == tmp_path / "custom.json"
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
"""Tests for the Claude Code persona prepend logic."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from pydantic_ai.messages import ModelRequest, SystemPromptPart, UserPromptPart
|
|
6
|
-
|
|
7
|
-
from pydantic_ai_claude_code import config
|
|
8
|
-
from pydantic_ai_claude_code.model import _prepend_persona
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
def test_persona_prepended_to_leading_request() -> None:
|
|
12
|
-
messages = [ModelRequest([SystemPromptPart("You are a helpful assistant."), UserPromptPart("hi")])]
|
|
13
|
-
out = _prepend_persona(messages)
|
|
14
|
-
leading = out[0]
|
|
15
|
-
assert isinstance(leading, ModelRequest)
|
|
16
|
-
persona, user_system = leading.parts[:2]
|
|
17
|
-
assert isinstance(persona, SystemPromptPart)
|
|
18
|
-
assert persona.content == config.CLAUDE_CODE_SYSTEM_PROMPT
|
|
19
|
-
assert isinstance(user_system, SystemPromptPart)
|
|
20
|
-
assert user_system.content == "You are a helpful assistant."
|
|
21
|
-
# The user prompt is untouched.
|
|
22
|
-
assert leading.parts[2].content == "hi" # type: ignore[attr-defined]
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def test_persona_prepend_is_idempotent() -> None:
|
|
26
|
-
messages = [ModelRequest([SystemPromptPart("hi")])]
|
|
27
|
-
once = _prepend_persona(messages)
|
|
28
|
-
twice = _prepend_persona(once)
|
|
29
|
-
parts = twice[0].parts # type: ignore[attr-defined]
|
|
30
|
-
assert (
|
|
31
|
-
sum(1 for p in parts if isinstance(p, SystemPromptPart) and p.content == config.CLAUDE_CODE_SYSTEM_PROMPT) == 1
|
|
32
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__main__.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/config.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/credentials.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/flow.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/provider.py
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/py.typed
RENAMED
|
File without changes
|
{pydantic_claude_code-0.6.2 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/updates.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|