pydantic-claude-code 0.6.1__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.1 → pydantic_claude_code-0.7.0}/PKG-INFO +29 -8
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/README.md +28 -7
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/install.sh +3 -3
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/pyproject.toml +1 -1
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__init__.py +1 -1
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/auth.py +1 -1
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/clai2.py +128 -39
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/config.py +0 -1
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/flow.py +44 -18
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/model.py +6 -2
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/storage.py +28 -13
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_clai2.py +130 -10
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_flow.py +75 -4
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_install.py +1 -1
- {pydantic_claude_code-0.6.1 → 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.1 → pydantic_claude_code-0.7.0}/tests/test_storage.py +8 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/uv.lock +1 -1
- pydantic_claude_code-0.6.1/tests/test_model.py +0 -32
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/.github/workflows/ci.yml +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/.github/workflows/publish.yml +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/.gitignore +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/LICENSE +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/examples/basic.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/__main__.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/credentials.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/provider.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/py.typed +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/updates.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/conftest.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_callback_server.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_credentials.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_integration.py +0 -0
- {pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/tests/test_provider.py +0 -0
- {pydantic_claude_code-0.6.1 → 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,13 +115,17 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
|
|
|
115
115
|
|
|
116
116
|
### Sign in
|
|
117
117
|
|
|
118
|
-
Run `/login claude
|
|
119
|
-
prints the URL in case it doesn't.
|
|
118
|
+
Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
|
|
119
|
+
prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
|
|
120
|
+
(over SSH, or a remote box), open that URL on any machine and sign in. The
|
|
121
|
+
browser then ends on a `http://localhost:.../callback?code=...` page that fails
|
|
122
|
+
to load; copy that whole address and paste it at CLAI2's prompt, then press
|
|
123
|
+
Enter. CLAI2 counts the characters instead of echoing the code. Or open the settings menu with `/claude_code`
|
|
120
124
|
(or `C` on the plugin in `/plugins`), choose **Sign-in**, and press Enter.
|
|
121
125
|
|
|
122
126
|
### Pick a model
|
|
123
127
|
|
|
124
|
-
`/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
|
|
125
129
|
`/model` offers them right away, and `/model_settings` sets thinking mode,
|
|
126
130
|
effort, and the rest for each. On an older CLAI2, or for a model that isn't
|
|
127
131
|
listed, open `/add_model` and choose the `claude-code` provider, or type one
|
|
@@ -135,6 +139,17 @@ directly:
|
|
|
135
139
|
Headless runs work the same way:
|
|
136
140
|
`clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
|
|
137
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
|
+
|
|
138
153
|
### Settings menu
|
|
139
154
|
|
|
140
155
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -146,7 +161,8 @@ opens it. Every change is saved right away and applies from the next run.
|
|
|
146
161
|
| Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
|
|
147
162
|
|
|
148
163
|
`/claude_code logout` and `/claude_code status` do the
|
|
149
|
-
same without the menu
|
|
164
|
+
same without the menu; add a profile name (`/claude_code logout work`) for
|
|
165
|
+
another account.
|
|
150
166
|
|
|
151
167
|
### Where the sign-in lives
|
|
152
168
|
|
|
@@ -165,7 +181,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
|
|
|
165
181
|
after switching.
|
|
166
182
|
|
|
167
183
|
If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
|
|
168
|
-
expired`, run `/login claude`. If the
|
|
184
|
+
expired`, run `/login claude-code`. If the
|
|
169
185
|
plugin fails to load with `cannot import name 'Plugin' from
|
|
170
186
|
'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
|
|
171
187
|
[Install](#install), or pin plugin 0.5.0.
|
|
@@ -178,6 +194,11 @@ provider. Instead of a `claude-code:` model string, construct
|
|
|
178
194
|
`ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
|
|
179
195
|
`ClaudeCodeProvider` by default.
|
|
180
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
|
+
|
|
181
202
|
### Quick start
|
|
182
203
|
|
|
183
204
|
```python
|
|
@@ -308,7 +329,7 @@ uv run pytest
|
|
|
308
329
|
|
|
309
330
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
310
331
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
311
|
-
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,
|
|
312
333
|
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
313
334
|
|
|
314
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,13 +86,17 @@ at it: `uv tool install pydantic-clai2 --with pydantic-claude-code`, then
|
|
|
86
86
|
|
|
87
87
|
### Sign in
|
|
88
88
|
|
|
89
|
-
Run `/login claude
|
|
90
|
-
prints the URL in case it doesn't.
|
|
89
|
+
Run `/login claude-code` (it was `/login claude` before 0.7.0). Your browser opens Claude's sign-in page, and CLAI2
|
|
90
|
+
prints the URL in case it doesn't. On a machine whose browser can't reach CLAI2
|
|
91
|
+
(over SSH, or a remote box), open that URL on any machine and sign in. The
|
|
92
|
+
browser then ends on a `http://localhost:.../callback?code=...` page that fails
|
|
93
|
+
to load; copy that whole address and paste it at CLAI2's prompt, then press
|
|
94
|
+
Enter. CLAI2 counts the characters instead of echoing the code. Or open the settings menu with `/claude_code`
|
|
91
95
|
(or `C` on the plugin in `/plugins`), choose **Sign-in**, and press Enter.
|
|
92
96
|
|
|
93
97
|
### Pick a model
|
|
94
98
|
|
|
95
|
-
`/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
|
|
96
100
|
`/model` offers them right away, and `/model_settings` sets thinking mode,
|
|
97
101
|
effort, and the rest for each. On an older CLAI2, or for a model that isn't
|
|
98
102
|
listed, open `/add_model` and choose the `claude-code` provider, or type one
|
|
@@ -106,6 +110,17 @@ directly:
|
|
|
106
110
|
Headless runs work the same way:
|
|
107
111
|
`clai2 -p "Summarize this repo" -m claude-code:claude-fable-5-1`.
|
|
108
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
|
+
|
|
109
124
|
### Settings menu
|
|
110
125
|
|
|
111
126
|
`/plugins configure claude_code`, `C` in `/plugins`, or a bare `/claude_code`
|
|
@@ -117,7 +132,8 @@ opens it. Every change is saved right away and applies from the next run.
|
|
|
117
132
|
| Credential storage | `auto` (`CLAUDE_CODE_CREDENTIALS`, else keyring, else a file), `keyring`, or `file` | plugin settings (`credentials`) |
|
|
118
133
|
|
|
119
134
|
`/claude_code logout` and `/claude_code status` do the
|
|
120
|
-
same without the menu
|
|
135
|
+
same without the menu; add a profile name (`/claude_code logout work`) for
|
|
136
|
+
another account.
|
|
121
137
|
|
|
122
138
|
### Where the sign-in lives
|
|
123
139
|
|
|
@@ -136,7 +152,7 @@ expire. Switching storage does not move an existing sign-in, so sign in again
|
|
|
136
152
|
after switching.
|
|
137
153
|
|
|
138
154
|
If a run says `Sign in to Claude Code first` or `Your Claude Code sign-in has
|
|
139
|
-
expired`, run `/login claude`. If the
|
|
155
|
+
expired`, run `/login claude-code`. If the
|
|
140
156
|
plugin fails to load with `cannot import name 'Plugin' from
|
|
141
157
|
'pydantic_clai2.plugins'`, your CLAI2 predates class-based plugins: upgrade it as described under
|
|
142
158
|
[Install](#install), or pin plugin 0.5.0.
|
|
@@ -149,6 +165,11 @@ provider. Instead of a `claude-code:` model string, construct
|
|
|
149
165
|
`ClaudeCodeModel('claude-fable-5-1')` directly; it connects itself to a
|
|
150
166
|
`ClaudeCodeProvider` by default.
|
|
151
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
|
+
|
|
152
173
|
### Quick start
|
|
153
174
|
|
|
154
175
|
```python
|
|
@@ -279,7 +300,7 @@ uv run pytest
|
|
|
279
300
|
|
|
280
301
|
To release, bump `version` in `pyproject.toml` and `__version__` in
|
|
281
302
|
`src/pydantic_ai_claude_code/__init__.py` (a test checks they match), merge, and
|
|
282
|
-
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,
|
|
283
304
|
builds, and uploads it to PyPI with the `PYPI_API_TOKEN` repository secret.
|
|
284
305
|
|
|
285
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.1 → 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.1 → 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.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/clai2.py
RENAMED
|
@@ -2,29 +2,36 @@
|
|
|
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
|
|
21
|
+
import sys
|
|
17
22
|
from collections.abc import Callable, Sequence
|
|
18
|
-
from typing import get_args
|
|
23
|
+
from typing import IO, Any, get_args
|
|
19
24
|
|
|
20
25
|
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
|
21
26
|
from pydantic_ai.exceptions import UserError
|
|
22
27
|
from pydantic_clai2.commands import Command
|
|
28
|
+
from termflow.tui.terminal import raw_mode
|
|
23
29
|
from pydantic_clai2.plugins import ModelProvider, Plugin, PluginHost, PluginLogin, SessionEnd, SessionStart, TurnEnd
|
|
30
|
+
from pydantic_clai2.ui.menus.menu_worker import menu_key, run_worker
|
|
24
31
|
from pydantic_clai2.ui.menus.field_menu import TERMINAL, FieldMenu, FieldRow, Runners, first_error, run_flow_async
|
|
25
32
|
|
|
26
33
|
from . import __version__, config, updates
|
|
27
|
-
from .flow import login
|
|
34
|
+
from .flow import login, parse_pasteback
|
|
28
35
|
from .model import ClaudeCodeModel
|
|
29
36
|
from .provider import ClaudeCodeProvider
|
|
30
37
|
from .storage import Backend, ClaudeCodeTokenStore, TokenStore, default_store
|
|
@@ -35,12 +42,30 @@ PREFIX = "claude-code"
|
|
|
35
42
|
COMMAND = "claude_code"
|
|
36
43
|
"""CLAI2 command names are Python identifiers, so the command cannot share the prefix's hyphen."""
|
|
37
44
|
|
|
38
|
-
LOGIN =
|
|
39
|
-
"""`/login claude` signs in."""
|
|
45
|
+
LOGIN = PREFIX
|
|
46
|
+
"""`/login claude-code` signs in, matching the `claude-code:` models it unlocks."""
|
|
40
47
|
|
|
41
48
|
SIGNED_IN = "signed in"
|
|
42
49
|
SIGNED_OUT = "not signed in"
|
|
43
|
-
_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}
|
|
44
69
|
|
|
45
70
|
|
|
46
71
|
class ClaudeCodeSettings(BaseModel):
|
|
@@ -54,9 +79,9 @@ class ClaudeCodeSettings(BaseModel):
|
|
|
54
79
|
)
|
|
55
80
|
|
|
56
81
|
|
|
57
|
-
def token_store(backend: Backend) -> TokenStore:
|
|
58
|
-
"""The store for a plugin setting; `auto` defers to `CLAUDE_CODE_CREDENTIALS`, as the package does."""
|
|
59
|
-
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)
|
|
60
85
|
|
|
61
86
|
|
|
62
87
|
class ClaudeCodeConfig:
|
|
@@ -73,9 +98,9 @@ class ClaudeCodeConfig:
|
|
|
73
98
|
self.settings = settings
|
|
74
99
|
self._save = save
|
|
75
100
|
|
|
76
|
-
def store(self) -> TokenStore:
|
|
77
|
-
"""The token store the current settings choose."""
|
|
78
|
-
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)
|
|
79
104
|
|
|
80
105
|
def rows(self) -> Sequence[FieldRow]:
|
|
81
106
|
"""The sign-in first, then where it is kept."""
|
|
@@ -131,7 +156,7 @@ class ClaudeCodeConfig:
|
|
|
131
156
|
|
|
132
157
|
|
|
133
158
|
class Providers:
|
|
134
|
-
"""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.
|
|
135
160
|
|
|
136
161
|
A provider is rebuilt when the stored sign-in differs from the one it holds: after signing in again here
|
|
137
162
|
or from another process. Refreshes the provider makes itself are saved back, so they keep it in step.
|
|
@@ -139,41 +164,88 @@ class Providers:
|
|
|
139
164
|
|
|
140
165
|
def __init__(self) -> None:
|
|
141
166
|
"""Start empty; a provider is built on the first run."""
|
|
142
|
-
self._cached: dict[Backend, ClaudeCodeProvider] = {}
|
|
167
|
+
self._cached: dict[tuple[Backend, str | None], ClaudeCodeProvider] = {}
|
|
143
168
|
|
|
144
|
-
def model(self, name: str, source: ClaudeCodeConfig) -> ClaudeCodeModel:
|
|
169
|
+
def model(self, name: str, source: ClaudeCodeConfig, profile: str | None = None) -> ClaudeCodeModel:
|
|
145
170
|
"""Build `name` on the stored sign-in, raising `UserError` with setup steps when there is none."""
|
|
146
|
-
|
|
147
|
-
store =
|
|
171
|
+
key = (source.settings.credentials, profile)
|
|
172
|
+
store = source.store(profile)
|
|
148
173
|
credentials = store.load()
|
|
149
174
|
if credentials is None:
|
|
150
|
-
raise UserError(f"Sign in to Claude Code first: /login {
|
|
151
|
-
provider = self._cached.get(
|
|
175
|
+
raise UserError(f"Sign in to Claude Code first: /login {_login(profile)}.")
|
|
176
|
+
provider = self._cached.get(key)
|
|
152
177
|
if provider is None or provider.credentials != credentials:
|
|
153
|
-
provider = self._cached[
|
|
178
|
+
provider = self._cached[key] = ClaudeCodeProvider(credentials, store=store)
|
|
154
179
|
return ClaudeCodeModel(name, provider=provider)
|
|
155
180
|
|
|
156
181
|
|
|
157
|
-
def status(source: ClaudeCodeConfig) -> str:
|
|
182
|
+
def status(source: ClaudeCodeConfig, profile: str | None = None) -> str:
|
|
158
183
|
"""One line on whether the plugin can run models, and where the sign-in lives."""
|
|
159
|
-
store = source.store()
|
|
184
|
+
store = source.store(profile)
|
|
160
185
|
where = f"the file {store.path}" if isinstance(store, ClaudeCodeTokenStore) else "the OS keyring"
|
|
161
186
|
if store.load() is None:
|
|
162
|
-
|
|
163
|
-
|
|
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}."
|
|
164
190
|
|
|
165
191
|
|
|
166
|
-
async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None]) -> str:
|
|
167
|
-
"""Sign in through the browser and save the tokens to the chosen store."""
|
|
168
|
-
|
|
192
|
+
async def sign_in(source: ClaudeCodeConfig, show_url: Callable[[str], None], profile: str | None = None) -> str:
|
|
193
|
+
"""Sign in through the browser, or a pasted redirect address, and save the tokens to the chosen store."""
|
|
194
|
+
store = source.store(profile)
|
|
195
|
+
await login(store=store, on_url=show_url, read_pasteback=lambda: run_worker(read_pasted_url))
|
|
169
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."
|
|
170
199
|
return f"Signed in to Claude Code. Choose a model in /add_model > {PREFIX}, or run /model {PREFIX}:{first}."
|
|
171
200
|
|
|
172
201
|
|
|
173
|
-
|
|
202
|
+
PASTE_PROMPT = "Or paste the address your browser ended on, then Enter (Esc cancels): "
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def read_pasted_url(keys: Callable[[], str] = menu_key, output: IO[str] = sys.stdout) -> str | None:
|
|
206
|
+
"""Read a pasted redirect address on one line, under the printed sign-in URL; `None` on Esc.
|
|
207
|
+
|
|
208
|
+
The address carries the authorization code, so it is counted, not echoed: a long URL would also wrap
|
|
209
|
+
and break the one-line redraw. `keys` is `run_worker`'s `menu_key`, which turns into `ctrl-c` when the
|
|
210
|
+
browser's callback wins and `login` cancels this read.
|
|
211
|
+
"""
|
|
212
|
+
chars: list[str] = []
|
|
213
|
+
note = ""
|
|
214
|
+
|
|
215
|
+
def draw() -> None:
|
|
216
|
+
shown = note or (f"[{len(chars)} characters]" if chars else "")
|
|
217
|
+
output.write(f"\r\x1b[K{PASTE_PROMPT}{shown}")
|
|
218
|
+
output.flush()
|
|
219
|
+
|
|
220
|
+
with raw_mode():
|
|
221
|
+
draw()
|
|
222
|
+
while True:
|
|
223
|
+
key = keys()
|
|
224
|
+
if key in ("escape", "ctrl-c"):
|
|
225
|
+
output.write("\r\n")
|
|
226
|
+
return None
|
|
227
|
+
if key == "enter":
|
|
228
|
+
if parse_pasteback("".join(chars)) is not None:
|
|
229
|
+
output.write("\r\n")
|
|
230
|
+
return "".join(chars)
|
|
231
|
+
note = "no authorization code in that; paste the whole address"
|
|
232
|
+
elif key == "backspace":
|
|
233
|
+
chars[-1:] = []
|
|
234
|
+
note = ""
|
|
235
|
+
elif key == "ctrl-u":
|
|
236
|
+
chars, note = [], ""
|
|
237
|
+
elif len(key) == 1 and key.isprintable():
|
|
238
|
+
chars.append(key)
|
|
239
|
+
note = ""
|
|
240
|
+
else:
|
|
241
|
+
continue
|
|
242
|
+
draw()
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def sign_out(source: ClaudeCodeConfig, profile: str | None = None) -> str:
|
|
174
246
|
"""Forget the stored tokens; runs with `claude-code:` models then ask to sign in again."""
|
|
175
|
-
source.store().delete()
|
|
176
|
-
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."
|
|
177
249
|
|
|
178
250
|
|
|
179
251
|
async def configure(source: ClaudeCodeConfig, show_url: Callable[[str], None], runners: Runners = TERMINAL) -> str:
|
|
@@ -190,7 +262,7 @@ async def configure(source: ClaudeCodeConfig, show_url: Callable[[str], None], r
|
|
|
190
262
|
|
|
191
263
|
|
|
192
264
|
class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
193
|
-
"""`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."""
|
|
194
266
|
|
|
195
267
|
def __init__(self, host: PluginHost, settings: ClaudeCodeSettings) -> None:
|
|
196
268
|
"""Build the provider and the menu's source once; CLAI2 loads the plugin again when settings change."""
|
|
@@ -199,15 +271,23 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
199
271
|
self._providers = Providers()
|
|
200
272
|
self._update: asyncio.Task[str | None] | None = None
|
|
201
273
|
self.provider = ModelProvider(
|
|
202
|
-
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),
|
|
203
279
|
)
|
|
204
280
|
|
|
205
281
|
def _resolve(self, name: str) -> ClaudeCodeModel:
|
|
206
282
|
return self._providers.model(name, self.source)
|
|
207
283
|
|
|
284
|
+
def _resolve_profile(self, name: str, profile: str) -> ClaudeCodeModel:
|
|
285
|
+
return self._providers.model(name, self.source, profile)
|
|
286
|
+
|
|
208
287
|
def _show_url(self, url: str) -> None:
|
|
209
288
|
self.host.console.print(
|
|
210
|
-
|
|
289
|
+
"Opening your browser to sign in to Claude Code. If it does not open, or this machine's browser "
|
|
290
|
+
f"cannot reach it (SSH, a remote box), open this anywhere and sign in:\n{url}",
|
|
211
291
|
markup=False,
|
|
212
292
|
soft_wrap=True,
|
|
213
293
|
)
|
|
@@ -216,11 +296,21 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
216
296
|
return (self.provider,)
|
|
217
297
|
|
|
218
298
|
def get_logins(self) -> Sequence[PluginLogin]:
|
|
219
|
-
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
|
+
)
|
|
220
307
|
|
|
221
308
|
async def _sign_in(self) -> str:
|
|
222
309
|
return await sign_in(self.source, self._show_url)
|
|
223
310
|
|
|
311
|
+
async def _sign_in_profile(self, profile: str) -> str:
|
|
312
|
+
return await sign_in(self.source, self._show_url, profile)
|
|
313
|
+
|
|
224
314
|
def get_commands(self) -> Sequence[Command]:
|
|
225
315
|
return (
|
|
226
316
|
Command(
|
|
@@ -239,11 +329,10 @@ class ClaudeCodePlugin(Plugin[ClaudeCodeSettings]):
|
|
|
239
329
|
async def _command(self, args: list[str]) -> str:
|
|
240
330
|
if not args:
|
|
241
331
|
return await self.configure()
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
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)
|
|
247
336
|
|
|
248
337
|
async def configure(self) -> str:
|
|
249
338
|
return await configure(self.source, self._show_url)
|
{pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/config.py
RENAMED
|
@@ -42,7 +42,6 @@ REDIRECT_HOST = "http://localhost"
|
|
|
42
42
|
REDIRECT_PATH = "callback"
|
|
43
43
|
CALLBACK_PORT_RANGE = (8765, 8795)
|
|
44
44
|
CALLBACK_TIMEOUT = 180
|
|
45
|
-
PASTEBACK_SCHEMES = ("claude://",)
|
|
46
45
|
|
|
47
46
|
# Request headers that must accompany Claude Code subscription tokens. `anthropic-beta` is
|
|
48
47
|
# appended (never replaced) by the auth layer so feature betas set by pydantic-ai survive.
|
{pydantic_claude_code-0.6.1 → pydantic_claude_code-0.7.0}/src/pydantic_ai_claude_code/flow.py
RENAMED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"""Authorization-code PKCE flow for Claude Code credentials.
|
|
2
2
|
|
|
3
3
|
The browser flow hosts a short-lived localhost callback server, the same shape as
|
|
4
|
-
the Codex provider's `_REDIRECT_URI`.
|
|
5
|
-
|
|
4
|
+
the Codex provider's `_REDIRECT_URI`. When the browser cannot reach it (SSH, a remote
|
|
5
|
+
box), the user can paste the address the browser ended on instead: see `read_pasteback`.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
from __future__ import annotations
|
|
@@ -13,7 +13,7 @@ import hashlib
|
|
|
13
13
|
import secrets
|
|
14
14
|
import threading
|
|
15
15
|
import webbrowser
|
|
16
|
-
from collections.abc import Callable
|
|
16
|
+
from collections.abc import Awaitable, Callable
|
|
17
17
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
18
18
|
from urllib.parse import parse_qs, urlencode
|
|
19
19
|
|
|
@@ -124,20 +124,20 @@ def _token_headers() -> dict[str, str]:
|
|
|
124
124
|
|
|
125
125
|
|
|
126
126
|
def parse_pasteback(raw: str) -> tuple[str, str] | None:
|
|
127
|
-
"""Parse
|
|
127
|
+
"""Parse what the user pasted into `(code, state)`; `None` when it holds no authorization code.
|
|
128
128
|
|
|
129
|
-
|
|
129
|
+
Accepts the address the browser ended on (`http://localhost:PORT/callback?code=...&state=...`, or
|
|
130
|
+
`claude://...`), just its query string, or the `code#state` form Anthropic's code page shows.
|
|
130
131
|
"""
|
|
131
|
-
|
|
132
|
+
text = raw.strip()
|
|
133
|
+
if "?" in text or text.startswith("code="):
|
|
134
|
+
params = parse_qs(text.partition("?")[2] if "?" in text else text)
|
|
135
|
+
code, state = params.get("code", [""])[0], params.get("state", [""])[0]
|
|
136
|
+
elif "#" in text:
|
|
137
|
+
code, _, state = text.partition("#")
|
|
138
|
+
else:
|
|
132
139
|
return None
|
|
133
|
-
|
|
134
|
-
query = raw.partition("?")[2]
|
|
135
|
-
params = parse_qs(query)
|
|
136
|
-
except ValueError:
|
|
137
|
-
return None
|
|
138
|
-
code = params.get("code", [""])[0]
|
|
139
|
-
state = params.get("state", [""])[0]
|
|
140
|
-
if not code:
|
|
140
|
+
if not code or any(char.isspace() for char in code + state):
|
|
141
141
|
return None
|
|
142
142
|
return code, state
|
|
143
143
|
|
|
@@ -182,7 +182,10 @@ def _print_url(url: str) -> None:
|
|
|
182
182
|
|
|
183
183
|
|
|
184
184
|
async def login(
|
|
185
|
-
*,
|
|
185
|
+
*,
|
|
186
|
+
store: TokenStore | None = None,
|
|
187
|
+
on_url: Callable[[str], None] = _print_url,
|
|
188
|
+
read_pasteback: Callable[[], Awaitable[str | None]] | None = None,
|
|
186
189
|
) -> ClaudeCodeCredentials:
|
|
187
190
|
"""Run the full OAuth flow and persist the minted credentials.
|
|
188
191
|
|
|
@@ -191,6 +194,10 @@ async def login(
|
|
|
191
194
|
Args:
|
|
192
195
|
store: The token store to write to. Defaults to the standard store.
|
|
193
196
|
on_url: Shows the authorization URL, in case the browser does not open. Prints it by default.
|
|
197
|
+
read_pasteback: Reads the address the browser ended on, for a browser that cannot reach this
|
|
198
|
+
machine's localhost callback (SSH, a remote box). Returns `None` to cancel. Runs alongside
|
|
199
|
+
the callback, which cancels it when the browser gets through first. Without it the
|
|
200
|
+
callback is the only way in, and it times out.
|
|
194
201
|
|
|
195
202
|
Returns:
|
|
196
203
|
The credentials that were persisted.
|
|
@@ -198,6 +205,9 @@ async def login(
|
|
|
198
205
|
if store is None:
|
|
199
206
|
store = default_store()
|
|
200
207
|
server = start_login_callback_server()
|
|
208
|
+
timeout = None if read_pasteback is not None else config.CALLBACK_TIMEOUT
|
|
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
|
|
201
211
|
try:
|
|
202
212
|
redirect_uri = f"{config.REDIRECT_HOST}:{server.server_address[1]}/{config.REDIRECT_PATH}"
|
|
203
213
|
flow = ClaudeCodeOAuthFlow(redirect_uri=redirect_uri)
|
|
@@ -206,9 +216,13 @@ async def login(
|
|
|
206
216
|
# Launch the browser off the event path: on some macOS setups `webbrowser.open`
|
|
207
217
|
# hangs until the UI settles, which would starve the callback wait below.
|
|
208
218
|
threading.Thread(target=_open_browser, args=(url,), daemon=True).start()
|
|
209
|
-
|
|
219
|
+
await asyncio.wait({callback} if paste is None else {callback, paste}, return_when=asyncio.FIRST_COMPLETED)
|
|
220
|
+
if server.query is not None:
|
|
221
|
+
code, state = _parse_callback_query(server.query)
|
|
222
|
+
elif paste is not None and paste.done():
|
|
223
|
+
code, state = _pasted(paste.result())
|
|
224
|
+
else:
|
|
210
225
|
raise UserError("Claude Code OAuth callback timed out.")
|
|
211
|
-
code, state = _parse_callback_query(server.query)
|
|
212
226
|
if state and state != flow.state:
|
|
213
227
|
raise UserError("Claude Code OAuth state mismatch; the redirect may be a replay.")
|
|
214
228
|
if not code:
|
|
@@ -217,12 +231,24 @@ async def login(
|
|
|
217
231
|
finally:
|
|
218
232
|
server.shutdown()
|
|
219
233
|
server.server_close()
|
|
220
|
-
# Release the waiting thread at once when the login was cancelled.
|
|
234
|
+
# Release the waiting thread at once when the login was cancelled or a paste won.
|
|
221
235
|
server.received.set()
|
|
236
|
+
if paste is not None and not paste.done():
|
|
237
|
+
paste.cancel()
|
|
238
|
+
await asyncio.gather(callback, *(() if paste is None else (paste,)), return_exceptions=True)
|
|
222
239
|
store.save(credentials)
|
|
223
240
|
return credentials
|
|
224
241
|
|
|
225
242
|
|
|
243
|
+
def _pasted(text: str | None) -> tuple[str, str]:
|
|
244
|
+
if text is None:
|
|
245
|
+
raise UserError("Claude Code sign-in cancelled.")
|
|
246
|
+
parsed = parse_pasteback(text)
|
|
247
|
+
if parsed is None:
|
|
248
|
+
raise UserError("That paste has no authorization code; copy the whole address your browser ended on.")
|
|
249
|
+
return parsed
|
|
250
|
+
|
|
251
|
+
|
|
226
252
|
def _open_browser(url: str) -> None:
|
|
227
253
|
try:
|
|
228
254
|
webbrowser.open(url)
|